Ragrig — RAG framework for Research and Prototyping

A trait-driven Retrieval-Augmented Generation library built around three independently swappable AI agents — Embed, Memory, and Chat — each behind a Rust trait that allows hot-swapping backends at runtime.
Designed for students and researchers. The default build compiles with
zero external dependencies — no C++ toolchain, no cmake, no protoc.
Install Rust, install Ollama, and you're done.
🔧 ragrig is the library crate. The terminal REPL binary lives in ragrig‑cli — install with
cargo install ragrig-cli(on crates.io soon) or clone from GitHub. Build your own application on top of the same traits the REPL uses.
- Zero extra dependencies — default build is pure Rust; Ollama provides models at runtime
- Trait-driven — every pipeline stage is a
Box<dyn Trait>; add new backends (OpenAI, Anthropic, Groq, …) or document parsers without touching existing code - Hardware-aware — delegate heavy models to the cloud, run small models locally, or go fully offline with CPU-only Fastembed (compiled into the binary)
- Hot-swappable — switch chat, memory, or embedding engines at runtime without losing document index or conversation context
- Token-efficient cloud usage — use a tiny local model for query rewriting and only send the final prompt + context to an expensive cloud API
- Hybrid retrieval — BM25 full-text search fused with cosine vector similarity via Reciprocal Rank Fusion. Hot-swappable ranking algorithms (RRF, weighted linear, MMR diversity, LLM re-rank) let you experiment with retrieval strategies without changing your document index
- Pluggable ranking — the
Rankertrait decouples scoring from storage; compare Cosine vs. BM25 vs. RRF fusion on the same document set at runtime - Cross-platform — Linux, macOS, WSL, and Windows (MSVC / MinGW)
What is RAG?
Retrieval-Augmented Generation lets an LLM answer questions about documents it has never seen before. Instead of stuffing every document into the prompt (which would overflow the context window), RAG works in two phases:
-
Indexing — Documents are split into overlapping chunks, each chunk is converted to a numeric embedding vector (a list of floats that captures its meaning), and both the text and its vector are saved in a vector store.
-
Querying — When you ask a question, the same embedding model converts your query to a vector. The store finds the k most similar chunks (via cosine similarity, BM25 keyword matching, or a hybrid of both). Those chunks are injected into the LLM prompt alongside your question, so the model can ground its answer in your documents.
Ragrig wraps this pipeline in three swappable agents — Embed (vectorise), Memory (optionally rewrite the query for better retrieval), and Chat (generate the final answer). The diagram below shows how data flows through the system:
flowchart LR
U[User query] --> M[Memory]
M -->|rewritten query| E[Embed]
E -->|query vector| V[(Vector Store)]
V -->|top-k chunks| C[Chat]
U -->|original query| C
C -->|grounded answer| R[Response]
If you are new to these concepts, a more detailed introduction can be found at retrieval-augmented-generation on the Prompt Engineering Guide.
Quick Start (Library)
Add ragrig to your Cargo.toml:
[]
= "0.9"
You need two things
- Rust — rustup.rs
- Ollama — ollama.com/download (provides models at runtime)
Pull the models you need:
Index and query in 4 function calls
use ;
use Path;
let embedder = Ollama .build?;
let chat = Ollama .build?;
let parsers = new;
let store = open_store.await?;
// Index
collect_documents.await?;
// Search
let results = search_similar.await?;
// Generate
chat.generate.await?;
Model parameters
Control generation with GenerationParams:
use ;
let agent = Ollama .build?;
See examples/pseudonymizer for a
complete multi-turn pseudonymization loop.
Three-Agent Architecture
Every pipeline stage is a trait object — swap any agent at runtime without losing your document index or conversation memory.
Documents (PDF/EPUB/DOCX/HTML)
│
▼
chunkedrs — token-accurate splitting with overlap
│
├── Embedder trait ──────────────────────────────────────────┐
│ OllamaEmbedder (local, nomic-embed-text) │
│ FastembedEmbedder (CPU-only, Nomic-Embed-Text-v1.5) │
│ NoopEmbedder (pure chat, no document search) │
│ │
▼ │
VectorStore trait ────────────────────────────────────────────────┤
BruteForceStore (pure Rust, MessagePack on disk) ← default │
LanceDbStore (Arrow columnar, hybrid BM25+vector) │
│ │
▼ │
Query
│
▼
Memory strategy (MemoryStrategy trait) ← hot-swap: /memory
RewriteMemory / TranscriptMemory
│
▼
Embed → VectorStore.search → Ranker → top-k chunks
│
▼
Chat agent (Generator trait) ← hot-swap: /chat
OllamaGenerator / DeepSeekGenerator
│
▼
Streamed response with retrieved context + conversation memory
Hybrid Search Tuning
The vector store uses Reciprocal Rank Fusion (RRF, k=60) to combine cosine vector similarity with BM25 full-text search. Two parameters control retrieval quality:
| Parameter | Default | What it does |
|---|---|---|
top_k |
50 | Maximum chunks injected into the prompt |
similarity_threshold |
0.04 | Cosine pre‑filter — chunks with cosine < threshold are excluded from RRF fusion |
Understanding the threshold:
- The threshold operates on cosine similarity (range: 0.0–1.0).
- RRF fusion produces scores in the 0.0–0.03 range (rank‑based, not similarity‑based). The trace output shows RRF scores, not cosine scores.
- A threshold of
0.0passes everything;0.04filters out chunks with negligible vector overlap while letting BM25 keyword matches through. - Values above ~0.05 will aggressively prune — use when you have high‑quality embeddings and want strictly semantic results.
Tune at runtime:
Query > /search # show current values
Query > /search topk 10 # fewer chunks, tighter context
Query > /search threshold 0.08 # stricter semantic filter
Hot-Swap Examples
Start with everything local, switch chat to cloud mid-session:
Query > /chat deepseek deepseek-chat sk-...
Chat agent swapped: Ollama (gemma2:latest) → DeepSeek (deepseek-chat)
Forgetful mode — ask Alice's name, then make her forget:
Query > My name is Alice
Assistant > Nice to meet you, Alice!
Query > /memory off
Memory disabled (was: Ollama qwen2.5:1.5b)
Query > What's my name?
Assistant > I don't know — you haven't told me yet.
Raw transcript — no query rewriting, test context-window pressure:
Query > /memory transcript
Memory strategy: rewrite → transcript
Query > What is a vector database?
Assistant > A vector database stores embeddings ...
Query > Can you summarize that?
# "that" is NOT rewritten — the raw transcript in the prompt
# provides context. Good for testing how models handle growing
# context windows with full conversation memory appended.
Session persistence — exit, restart, and recall past context:
Query > What are random effects in meta-analysis?
Assistant > Random effects models assume that the true effect size
varies across studies, as opposed to a single fixed effect …
Query > /exit
# next day …
$ ragrig --folder ~/papers
Session: 1718400000
Query > /memory log
History diffusion: off → log
Query > What was I asking about yesterday?
# The chat prompt now includes the raw transcript of the previous
# session, so the model can pick up the thread without you
# repeating yourself.
Assistant > Yesterday you asked about random effects in
meta-analysis. We discussed how they differ from fixed-effect
models …
Pure chat — no document search, no memory, cloud-only:
Query > /embed none
Query > /memory off
Query > /chat deepseek deepseek-v4-pro
Query > Explain quantum entanglement in one paragraph.
Switch embeddings to CPU-only (no network):
Query > /embed fastembed
Embedder swapped: Ollama (nomic-embed-text) → Fastembed (Nomic-Embed-Text-v1.5)
Experiment with ranking algorithms — same index, different retrieval:
Query > /search rank Cosine
Ranker set to Cosine.
Query > /search rank BM25
Ranker set to BM25.
Query > /search rank Weighted alpha 0.7
Ranker set to Weighted.
Query > /search rank MMR lambda 0.7 inner Cosine
Ranker set to MMR.
Query > /search rank LLM inner Cosine model qwen2.5:0.5b
LLM reranker using Ollama (qwen2.5:0.5b)
Ranker set to LLM.
Compilation Paths
Default — Zero extra dependencies (recommended)
Nothing to install beyond Rust itself. Uses a pure-Rust vector store (custom BM25 + cosine similarity + RRF fusion, persisted to MessagePack). Embeddings come from Ollama over HTTP at runtime.
This is the path we ship to students. It compiles without a C++ toolchain,
cmake, or protoc — works on Windows, macOS, and Linux with zero platform
friction.
Internal embeddings — Fastembed (CPU-only)
Adds FastembedEmbedder — runs Nomic-Embed-Text-v1.5 on
the CPU. Zero network overhead for embeddings. Needs a C compiler (gcc
or cl.exe) at build time. Use /embed fastembed at runtime.
LanceDB backend (large collections)
Adds Arrow C++, protobuf, and compression codecs.
Requires cmake and protoc at build time. Faster hybrid search for
collections with 100k+ chunks.
Feature flags
| Flag | Default | Description |
|---|---|---|
ollama-embed |
on | Local embeddings via Ollama HTTP (no extra deps) |
internal |
on | Pure-Rust vector store (MessagePack + cosine + BM25) |
internal-embed |
off | In-process Fastembed embeddings (needs C compiler) |
internal-generate |
off | In-process Candle LLM — zero network inference |
offline |
off | Meta: enables internal + internal-embed + internal-generate |
lancedb |
off | LanceDB hybrid index (needs protoc, Arrow C++) |
test-fixtures |
off | Compile-time embedded test documents for downstream crates |
kreuzberg |
off | Kreuzberg PDF parser (OCR, layout, DOCX) |
The offline feature is a convenience meta-flag that enables every local
component: chat, embeddings, and vector store all run in-process with zero
network dependencies. Use offline-cuda, offline-metal, or offline-mkl
for GPU-accelerated variants.
Requirements
| Dependency | When needed |
|---|---|
| Rust 1.94+ | Build (always) |
| Ollama | Runtime — provides chat, embed, and memory models |
C compiler (gcc/cl.exe) |
Only with internal-embed feature |
C++ toolchain, protoc, cmake |
Only with lancedb feature |
Default build: Rust + Ollama. Nothing else.
Platform Setup
Linux / macOS / WSL
|
Windows
- Install Rust from rustup.rs (MSVC host triple, the default)
- Run
cargo build --release
No extra tools needed. If you later want Fastembed (--features internal-embed),
install the Visual C++ Build Tools
(select "C++ build tools" workload).
For the REPL commands, CLI flags, and interactive usage, see the
ragrig-binREADME.
API Usage (Developers)
ragrig is a library. Build your own frontend — GUI, web server, headless bot — on top of the same traits.
use ;
use Path;
// Build agents and parser registry
let embedder = Ollama .build?;
let chat_agent = Ollama
.build?;
let parsers = new;
let folder = new;
let chunk_cfg = default;
let store = open_store.await?;
// Index documents
let _stats = collect_documents.await?;
// Search
let results = search_similar.await?;
// Chat
chat_agent.generate_stream.await?;
Configuration profiles
RagrigConfig is the library's single format-agnostic configuration surface.
It composes four sub-configs (ChatConfig, EmbedConfig, ParseConfig,
MemoryConfig) and derives Serialize + Deserialize — so the same struct
works for CLI arguments, JSON, TOML, or programmatic construction.
Three entry points:
use RagrigConfig;
// 1. Programmatic — builder-style via Default + struct update
let config = RagrigConfig ;
// 2. From a JSON file (zero extra dependencies — serde_json is already included)
let json = read_to_string?;
let config: RagrigConfig = from_str?;
// 3. From a TOML file (add `toml = "0.8"` to Cargo.toml)
let toml_str = read_to_string?;
let config: RagrigConfig = from_str?;
Example TOML profile — save this as profile.toml and load it at startup
via a small wrapper binary, or deserialise it programmatically:
= "./research-papers"
= "s2k-xxxxxxxxxxxx"
[]
= "Ollama"
= "gemma2:latest"
= 8192
= "Auto"
[]
= 0.1
= 2048
[]
= "Ollama"
= "nomic-embed-text"
= 20
= 0.04
[]
= "Extract"
= 512
= 64
[]
= "qwen2.5:1.5b"
Merging CLI overrides on top of a profile — use override_with() to
apply only the fields the user explicitly changed on the command line:
// Load the base profile
let mut config: RagrigConfig = from_str?;
// Parse CLI args and convert to a RagrigConfig (binary-side code)
let cli_config = from;
// Merge: CLI values override profile values where they differ from defaults
config.override_with;
Adding a new backend
Implement the Generator, Embedder, VectorStore, or DocumentParser trait:
Then wire it into ChatAgentSpec::parse("openai", ...) — no other code changes needed.
Implementing a new document parser
Add support for a new PDF backend or file format (~30 lines). Example using
justpdf (pure-Rust PDF library):
use DocumentParser;
use Path;
;
Then register it in parsers::build_parsers() (or hot-swap via /parser pdf justpdf
once you add the variant to PdfParserBackend). The chunker, embedder, and search
pipeline all work unchanged — they only see Markdown.
Implementing a custom memory strategy
Memory backends implement the [MemoryStrategy] trait. The trait controls
only query rewriting — the session always replays the raw transcript whenever
*a strategy is active, regardless of whether rewriting happened.
Example: a strategy that rewrites using only the immediately preceding turn, discarding older turns so the rewriter isn't distracted by stale context:
use async_trait;
use ;
The trait provides three methods:
| Method | Purpose |
|---|---|
generate_rewrite(prompt) -> Option<String> |
Return Some(rewritten) to replace the query before vector search, or None to use the raw query. |
clear() |
Wipe persistent state (default no-op). |
name() |
Label displayed in /memory output. |
Built-in strategies (RewriteMemory, TranscriptMemory) cover the common
cases; implement the trait directly when you need custom truncation, keyword
extraction, or external rewriter services.
Implementing a custom history strategy
History backends implement the [HistoryStrategy] trait from
ragrig::longterm_memory. The trait controls how past sessions are
diffused into the current chat prompt.
Example: a strategy that loads only the most recent session, formats a compact summary header, and skips the full transcript:
use async_trait;
use ;
;
The trait provides two methods:
| Method | Purpose |
|---|---|
build_context(store, query) -> String |
Return a preamble injected into the system prompt. Return "" to skip. |
name() |
Label displayed in /memory output. |
Built-in strategies (LogHistory, SummaryHistory) cover the common cases;
implement the trait directly when you need custom filtering, selection from
multiple sessions, or non-LLM recombination.
Implementing a custom ranker
The [Ranker] trait lets you plug in any scoring algorithm. Implement
rank(), name(), and clone_box():
use ;
;
The built-in rankers — HybridRrfRanker, WeightedFusionRanker,
MmrDiversityRanker, and LlmReranker — already cover the most common
retrieval strategies. The decorator pattern (MmrDiversityRanker and
LlmReranker) lets you wrap any inner ranker for diversity or LLM re-ranking.
Test fixtures for downstream crates
Enable the test-fixtures feature to get compile-time embedded copies of
ragrig's own test documents — PDF, R Markdown, and HTML files suitable for
writing parser integration tests without shipping your own files.
# Cargo.toml
[]
= { = "0.5", = ["test-fixtures"] }
use fixtures;
// Also available as named constants:
assert!;
assert!;
Reactive UI integration (egui, ratatui, web, …)
Streaming generation to a GUI or TUI is a 4-call pattern. The same slim API works identically in egui, ratatui, a web server (SSE), or any reactive framework:
use ;
use mpsc;
// 1. Build the agent — one line
let agent = Ollama .build?;
// 2. Run generation on a background runtime, bridge to UI via channel
let = ;
let agent = new;
let agent_clone = agent.clone;
new?.spawn;
// 3. Drain tokens in the UI loop (called every frame / event loop tick)
That's it — 4 ragrig calls: build, spawn, generate_stream, try_recv.
The remaining 95% of a chat UI is framework-specific layout and input
handling, not ragrig. See examples/streaming_chat_egui/ and
examples/streaming_chat_ratatui/ for complete runnable demos.
Typed errors
ragrig defines typed error variants in [RagrigError] that carry
structured payloads so callers can recover programmatically:
| Variant | Payload | Recovery |
|---|---|---|
ContextSizeExceeded |
current, max (tokens) |
Reduce top_k or expand context window |
EmbedModelNotFound |
model: String |
Run ollama pull {model} and retry |
StoreCorrupt |
path: String |
Delete the store file and re-index |
NoDocumentsFound |
folder: String |
Add PDF, EPUB, or HTML files to the folder |
OllamaUnreachable |
context: String |
Start Ollama with ollama serve — see troubleshooting for common causes |
GenerationFailed |
backend, model, detail |
Check model is pulled and fits in VRAM |
Every variant provides a [suggested_action()] method with a
human-readable recovery hint. Use [RagrigError::log_or()] to
log the error and its action in one call.
Downcast from anyhow::Error and switch on the variant:
use RagrigError;
let result = agent.generate_with_context.await;
match result
Runnable examples
Clone the repo and run any example with cargo run in its directory
(an Ollama server must be running):
# Single-shot RAG query — index fixtures, search, generate
# Two-agent dialog with shared vector store and transcript
# Streaming chat GUI with markdown bubbles (egui)
# Streaming chat TUI with two-color bubbles (ratatui)
# Streaming chat GUI with chat bubbles, provider/model picker, and RAG folder (Iced)
# Binary with embedded vector store — indexed at build time
| Example | Concept |
|---|---|
rag_query |
Single-shot pipeline: index → embed → search → generate via RagAgent |
dialog |
Multi-agent orchestration: two RagAgent instances sharing one vector store and one transcript |
streaming_chat_egui |
Reactive GUI: generate_stream + channel bridge → egui markdown bubbles |
streaming_chat_ratatui |
Reactive TUI: same channel pattern → ratatui two-color bubbles with scroll |
streaming_chat_iced |
Reactive GUI: Iced native GUI with provider/model picker, RAG folder picker, and streaming chat bubbles |
embedded_togo |
Embedded store: build.rs indexes fixtures at compile time, include_bytes! bakes it into the binary |
Transcripts
The TurnPairs newtype converts a session's Vec<Turn> into a slice of
(&str, &str) pairs suitable for RagAgent::generate_with_context():
use ;
let turns = vec!;
let pairs = from;
agent.generate_with_context.await?;
Q & A
What is unique about ragrig and why should I use it?
Ragrig tries to be a flexible and zero-friction prototyping tool for researchers and students, not an enterprise-grade framework with all bells and whistles. Here are the points that distinguish Ragrig from other crates:
Zero native dependencies in default build.** Every other crate needs at minimum a C compiler (for tokenizers, ONNX runtime, tree-sitter, etc.) or an API key. Ragrig builds with cargo build --release and nothing else. This is a genuinely unique selling point for students, workshops, and quick-start scenarios.
-
Runtime hot-swapping via trait objects. Every other crate uses compile-time feature flags to select backends. Ragrig lets you switch chat/embed/memory engines mid-session without losing state.
langchainrusthas multiple providers but you pick them atCargo.tomltime. ragrig's/chat deepseek,/embed fastembed,/memory offcommands have no equivalent in any competitor. -
Panic-safe multi-parser PDF pipeline. Three PDF parsers (pdfsink for layout-aware, pdf-extract for flat text, sloppy binary scavenger as fallback) with
catch_unwindwrapping. No other crate does this — they pick one parser and crash on malformed PDFs. -
Token-efficient cloud usage pattern. Use a tiny local model for query rewriting, only send the final prompt + context to the cloud. This is described in the README hot-swap examples and baked into the MemoryStrategy trait. No competitor has this pattern explicitly designed in.
-
Student-focused UX. The README's quick-start is 3 commands (
rustup,ollama pull ×3,cargo build --release). The REPL has 15+ slash commands with clear transition messages. Session persistence works out of the box.
When should I not use it?
Ragrig is designed as an accessible framework to build multi-agent interactive prototypes. It is not intended for production use or highly scalable deployments. For these purposes, you should use a dedicated RAG framework like rig-core on which Ragrig is heavily based.
I am a Python programmer. I am not able to program in Rust. How can I use Ragrig?
Ragrig provides a fully documented API with numerous examples and a dedicated agent skill (only available on Github). With this information, a good coding agent can produce working Ragrig applications with not more than a few instructions.
For version 2.0, we plan to provide Python (and possibly R) bindings.
Ollama is unreachable — what should I check?
If ragrig reports OllamaUnreachable, work through these in order:
-
Ollama isn't running. Start it in a terminal:
On macOS and Windows, launching the Ollama desktop app also starts the server.
-
Ollama is running on a non-default port. By default ragrig connects to
localhost:11434. If you changed the port (e.g. viaOLLAMA_HOST), set the same variable in the terminal where ragrig runs: -
A model pull was interrupted. Partial downloads can leave the Ollama registry in a broken state. Re-pull the model:
If that fails, remove the partial model and pull fresh:
&& -
Firewall or port conflict. Ensure port 11434 is not blocked by a firewall or already bound by another process:
# Linux / macOS / WSL # Windows (PowerShell) | -
WSL → Windows networking. When Ollama runs on Windows and ragrig runs inside WSL,
localhostdoes not automatically forward. Find the Windows host IP from inside WSL and setOLLAMA_HOST:Alternatively, install Ollama directly inside WSL so both processes share the same network namespace.
When the context size exceeds the model's maximum, how can I adjust this?
Context-size errors happen for two reasons:
- Hardware VRAM limits — Ollama caps the context window at 4096 tokens on GPUs with less than 24 GB VRAM to prevent out-of-memory crashes.
- Architectural limits — some distilled reasoning models (e.g. DeepSeek R1 8B/14B) have a hard-coded 4096-token maximum that even Ollama cannot override.
Ragrig detects context overflows automatically. By default, when the model
reports a [RagrigError::ContextSizeExceeded], the binary auto-adjusts its
budget to the model's actual maximum, rebuilds the prompt with fewer chunks,
and retries once. You see:
[INFO] Context overflow — shrinking budget to 9216 chars, retrying.
If the retry also fails, pass --context-size-forced to keep the original
error path, then set a manual budget:
# or mid-session:
Library consumers can catch the typed error directly:
match chat_agent.generate.await
Why does Generator::generate_stream take &self when my backend needs &mut self?
The trait is designed for stateless LLM backends (Ollama, DeepSeek) where a prompt-in/response-out call has no observable side-effects on the client. If your backend tracks session state — rule-usage counters, connection pools, an internal memory queue — you need interior mutability.
Solution: wrap the mutable state in Arc<Mutex<T>>:
use ;
Arc also gives you a trivial clone_box implementation — just
Arc::clone the inner handle. See
examples/eliza_generator for a
complete worked example wrapping the stateful eliza crate.
Why do I have to implement Debug on my Generator?
The Generator trait inherits Debug from its supertrait bound
(: Send + Sync + Debug). This is so the RagAgent can print a
human-readable representation of the active backend in diagnostic
output and log messages.
The problem: many useful types (Regex, raw file handles, opaque
third-party structs) don't implement Debug. Deriving fails, and
you're left writing a manual impl.
Solution: implement Debug by hand — it's two lines:
For fully opaque types, a placeholder string is fine:
.field
The point is that Debug is informational, not load-bearing — nothing
in the framework parses the output. If your backend fields are all
plain data (String, usize, bool), the derive works automatically
and you won't see this issue at all.
Why do I need async_trait even for a synchronous backend?
The Generator trait is declared with #[async_trait] so that every
backend — network, local, or pure computation — presents the same
async interface. This lets RagAgent call generate_stream().await
uniformly without knowing whether the backend makes HTTP requests or
runs a local regex loop.
The cost: one extra dependency (async-trait = "0.1") and one
extra annotation (#[async_trait] on the impl block). The method
body itself can be completely synchronous — async doesn't force you
to spawn tasks or touch the network:
The async keyword on the method signature is a promise to the caller
(the framework), not a requirement that your code be asynchronous.
License
MIT License — see LICENSE.