How dhanuk8778-netizen/agentic-rag-tool-routing- works
Purpose and execution
This is an offline, CPU-oriented Python stack for agentic RAG, multi-tool routing, parameter-efficient adaptation, and serving experiments. Models and synthetic datasets are trained locally; checkpoints and JSON results are persisted in-repo. Primary orchestration is scripts/run_full_pipeline.sh; stage entry points are src/train_retrieval_stack.py, src/train_router.py, and src/serving/agent_loop.py.
Data and model artifacts
Synthetic corpus, paraphrased retrieval queries, router queries, and tokenizers form the common training input layer: src/data/corpus.py, src/data/queries.py, src/data/router_queries.py. Trained weights/tokenizers are materialized under checkpoints/, including retrieval, router, and TinyGPT artifacts. YAML controls demo/full-scale runs: configs/retrieval_config.yaml, configs/router_config.yaml, configs/serving_config.yaml.
Retrieval stack
Retrieval is a staged candidate-and-rerank pipeline. BM25 provides lexical candidates; a shared Transformer-backed bi-encoder produces dense vectors; a vector store supports dense lookup; hybrid candidates can be reranked by a query-document cross-encoder. Core boundaries are src/retrieval/bm25.py, src/retrieval/bi_encoder.py, src/retrieval/vector_store.py, src/retrieval/cross_encoder.py, and orchestration in src/retrieval/pipeline.py. src/train_retrieval_stack.py trains both encoders, mines negatives from pipeline-like candidates, evaluates metrics, and writes retrieval results.
Semantic routing and validation
The router maps a query to one or more tools using a multi-label sigmoid classifier over the tool registry. src/router/semantic_router.py owns inference/training behavior, while src/router/tools.py defines routable capabilities. src/train_router.py trains and evaluates the router. Validation crosses an external-service boundary in src/router/llm_judge.py: it uses the Anthropic Claude API when ANTHROPIC_API_KEY is present, otherwise uses a deterministic local judge for reproducible offline operation.
PEFT / QLoRA adaptation
Router domain adaptation is implemented internally rather than delegated to bitsandbytes or a hosted model platform. Low-rank adapters, uniform affine quantization, and adaptation orchestration live in src/peft/lora.py, src/peft/quantization.py, and src/peft/finetune_router.py. The design freezes/quantizes the base model and trains adapters, with full fine-tuning available as a comparison path.
Serving runtime and optimizations
A minimal causal TinyGPT runtime supports generation and explicit KV-cache handling: src/serving/tiny_transformer.py, src/serving/kv_cache.py, src/serving/char_tokenizer.py. KV-cache benchmark execution is src/serving/run_kv_cache_benchmark.py. Speculative decoding coordinates draft and target TinyGPT models, verifies target-equivalent output, and is benchmarked by src/serving/speculative_decoding.py and src/serving/run_speculative_decoding.py. The attention implementation explicitly handles cache-aware causal-mask alignment rather than relying on incompatible default attention semantics.
End-to-end agent flow and observability
src/serving/agent_loop.py is the integration boundary: route an incoming task, invoke the RAG path when appropriate, and complete the task through selected tools. Evaluation metrics are centralized in src/eval/metrics.py and src/eval/retrieval_eval.py; stage outputs are persisted as JSON under results/. The architecture is intentionally measurable: retrieval quality, routing accuracy, PEFT adaptation, cache latency, and speculative-decoding correctness/performance are independently runnable stages.
Main entry points: train_retrieval_stack.py Retrieval Training · train_router.py Router Training · pipeline.py Retrieval Pipeline · agent_loop.py Agent Loop
Components 21
Inputs & Artifacts
- Synthetic Data & Tokenizers · Corpus, retrieval queries, router queries, and tokenizers.
src/data/corpus.py - Stage Configs · Controls retrieval, router, and serving run scales.
configs/retrieval_config.yaml - Checkpoints · Persisted retrieval, router, and TinyGPT weights and tokenizers.
Retrieval Stack
- BM25 Candidates
src/retrieval/bm25.py - Bi-Encoder · Shared Transformer encoder for query and document vectors.
src/retrieval/bi_encoder.py - Vector Store
src/retrieval/vector_store.py - Cross-Encoder
src/retrieval/cross_encoder.py - Retrieval Pipeline · Combines lexical and dense candidates before reranking.
src/retrieval/pipeline.py - Retrieval Training · Trains encoders, mines negatives, and evaluates retrieval.
src/train_retrieval_stack.py
Routing & Adaptation
- Tool Registry · Defines routable capabilities.
src/router/tools.py - Semantic Router · Maps queries to one or more registered tools.
src/router/semantic_router.py - QLoRA Router Adaptation · Freezes or quantizes the base model and trains low-rank adapters.
src/peft/finetune_router.py - Router Training
src/train_router.py - Router Judge · Uses Claude when configured, otherwise a deterministic local judge.
src/router/llm_judge.py
Serving & Agent Runtime
- Agent Loop · Routes tasks, invokes RAG when needed, and executes selected tools.
src/serving/agent_loop.py - TinyGPT Runtime · Supports explicit KV-cache-aware generation.
src/serving/tiny_transformer.py - KV Cache Benchmark
src/serving/run_kv_cache_benchmark.py - Speculative Decoding · Verifies target-equivalent output and benchmarks decoding.
src/serving/speculative_decoding.py
Evaluation & Outputs
- Evaluation Metrics · Shared retrieval, routing, adaptation, and serving measurements.
src/eval/metrics.py - JSON Results · Stage metrics and benchmark outputs.
Other components
- Full Pipeline · Runs the local training and serving experiment stages.
scripts/run_full_pipeline.sh
Connections 29
- Full Pipeline → Retrieval Training: runs
- Full Pipeline → Router Training: runs
- Full Pipeline → Agent Loop: runs
- Synthetic Data & Tokenizers → Retrieval Training: retrieval inputs
- Stage Configs → Retrieval Training: controls
- Retrieval Training → Bi-Encoder: trains
- Retrieval Training → Retrieval Pipeline: mines candidates
- BM25 Candidates → Retrieval Pipeline: lexical candidates
- Bi-Encoder → Vector Store: indexes vectors
- Vector Store → Retrieval Pipeline: dense candidates
- Retrieval Pipeline → Cross-Encoder: reranks
- Retrieval Training → Checkpoints: writes
- Synthetic Data & Tokenizers → Router Training: router queries
- Tool Registry → Semantic Router: labels tools
- QLoRA Router Adaptation → Semantic Router: adapts
- Router Training → QLoRA Router Adaptation: trains
- Router Training → Router Judge: validates
- Router Training → Checkpoints: writes
- Semantic Router → Agent Loop: routes tasks
- Agent Loop → Retrieval Pipeline: retrieves when needed
- Agent Loop → Tool Registry: invokes selected tools
- Checkpoints → TinyGPT Runtime: loads models
- TinyGPT Runtime → KV Cache Benchmark: measures cache latency
- TinyGPT Runtime → Speculative Decoding: draft and target models
- Retrieval Training → Evaluation Metrics: evaluates
- Router Training → Evaluation Metrics: evaluates
- Evaluation Metrics → JSON Results: persists JSON
- KV Cache Benchmark → JSON Results: persists benchmark
- Speculative Decoding → JSON Results: persists benchmark