# dhanuk8778-netizen/agentic-rag-tool-routing- architecture

> Architecture diagram of the GitHub repository dhanuk8778-netizen/agentic-rag-tool-routing-, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/dhanuk8778-netizen/agentic-rag-tool-routing-
- Repository: https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-

## Overview

#### 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: [`src/train_retrieval_stack.py`](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_retrieval_stack.py) (Retrieval Training), [`src/train_router.py`](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_router.py) (Router Training), [`src/retrieval/pipeline.py`](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/pipeline.py) (Retrieval Pipeline), [`src/serving/agent_loop.py`](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/agent_loop.py) (Agent Loop)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_inputs["Inputs &amp; Artifacts"]
  node_data["Synthetic Data &amp; Tokenizers<br/>training inputs<br/>[corpus.py]"]
  node_configs["Stage Configs<br/>YAML configuration"]
  node_checkpoints[("Checkpoints<br/>model artifacts")]
end

subgraph group_retrieval["Retrieval Stack"]
  node_bm25["BM25 Candidates<br/>lexical retriever<br/>[bm25.py]"]
  node_bi_encoder["Bi-Encoder<br/>dense retriever<br/>[bi_encoder.py]"]
  node_vector_store[("Vector Store<br/>dense index<br/>[vector_store.py]")]
  node_cross_encoder["Cross-Encoder<br/>reranker<br/>[cross_encoder.py]"]
  node_rag_pipeline["Retrieval Pipeline<br/>hybrid RAG pipeline<br/>[pipeline.py]"]
  node_train_retrieval["Retrieval Training<br/>training entry point"]
end

subgraph group_routing["Routing &amp; Adaptation"]
  node_tools["Tool Registry<br/>tool definitions<br/>[tools.py]"]
  node_semantic_router["Semantic Router<br/>multi-label classifier<br/>[semantic_router.py]"]
  node_router_adaptation["QLoRA Router Adaptation<br/>PEFT trainer<br/>[finetune_router.py]"]
  node_train_router["Router Training<br/>training entry point<br/>[train_router.py]"]
  node_llm_judge["Router Judge<br/>validation boundary<br/>[llm_judge.py]"]
end

subgraph group_serving["Serving &amp; Agent Runtime"]
  node_agent_loop{{"Agent Loop<br/>integration runtime<br/>[agent_loop.py]"}}
  node_tinygpt["TinyGPT Runtime<br/>causal generation runtime"]
  node_kv_benchmark["KV Cache Benchmark<br/>performance benchmark"]
  node_speculative["Speculative Decoding<br/>draft-target optimization"]
end

subgraph group_evaluation["Evaluation &amp; Outputs"]
  node_metrics["Evaluation Metrics<br/>evaluation library<br/>[metrics.py]"]
  node_results[("JSON Results<br/>persisted outputs")]
end

node_pipeline{{"Full Pipeline<br/>orchestrator"}}

node_pipeline -->|"runs"| node_train_retrieval
node_pipeline -->|"runs"| node_train_router
node_pipeline -->|"runs"| node_agent_loop
node_data -->|"retrieval inputs"| node_train_retrieval
node_configs -->|"controls"| node_train_retrieval
node_train_retrieval -->|"trains"| node_bi_encoder
node_train_retrieval -->|"mines candidates"| node_rag_pipeline
node_bm25 -->|"lexical candidates"| node_rag_pipeline
node_bi_encoder -->|"indexes vectors"| node_vector_store
node_vector_store -->|"dense candidates"| node_rag_pipeline
node_rag_pipeline -->|"reranks"| node_cross_encoder
node_train_retrieval -->|"writes"| node_checkpoints
node_data -->|"router queries"| node_train_router
node_tools -->|"labels tools"| node_semantic_router
node_router_adaptation -->|"adapts"| node_semantic_router
node_train_router -->|"trains"| node_router_adaptation
node_train_router -->|"validates"| node_llm_judge
node_train_router -->|"writes"| node_checkpoints
node_semantic_router -->|"routes tasks"| node_agent_loop
node_agent_loop -->|"retrieves when needed"| node_rag_pipeline
node_agent_loop -->|"invokes selected tools"| node_tools
node_checkpoints -->|"loads models"| node_tinygpt
node_tinygpt -->|"measures cache latency"| node_kv_benchmark
node_tinygpt -->|"draft and target models"| node_speculative
node_train_retrieval -->|"evaluates"| node_metrics
node_train_router -->|"evaluates"| node_metrics
node_metrics -->|"persists JSON"| node_results
node_kv_benchmark -->|"persists benchmark"| node_results
node_speculative -->|"persists benchmark"| node_results

click node_pipeline "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/scripts/run_full_pipeline.sh"
click node_data "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/data/corpus.py"
click node_configs "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/configs/retrieval_config.yaml"
click node_bm25 "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/bm25.py"
click node_bi_encoder "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/bi_encoder.py"
click node_vector_store "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/vector_store.py"
click node_cross_encoder "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/cross_encoder.py"
click node_rag_pipeline "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/pipeline.py"
click node_train_retrieval "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_retrieval_stack.py"
click node_tools "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/tools.py"
click node_semantic_router "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/semantic_router.py"
click node_router_adaptation "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/peft/finetune_router.py"
click node_train_router "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_router.py"
click node_llm_judge "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/llm_judge.py"
click node_agent_loop "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/agent_loop.py"
click node_tinygpt "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/tiny_transformer.py"
click node_kv_benchmark "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/run_kv_cache_benchmark.py"
click node_speculative "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/speculative_decoding.py"
click node_metrics "https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/eval/metrics.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_data,node_configs,node_checkpoints toneBlue
class node_bm25,node_bi_encoder,node_vector_store,node_cross_encoder,node_rag_pipeline,node_train_retrieval toneAmber
class node_tools,node_semantic_router,node_router_adaptation,node_train_router,node_llm_judge toneMint
class node_agent_loop,node_tinygpt,node_kv_benchmark,node_speculative toneRose
class node_metrics,node_results toneIndigo
class node_pipeline toneNeutral
```

## Components

### Inputs & Artifacts

- [Synthetic Data & Tokenizers](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/data/corpus.py): training inputs · Corpus, retrieval queries, router queries, and tokenizers. · `src/data/corpus.py`
- [Stage Configs](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/configs/retrieval_config.yaml): YAML configuration · Controls retrieval, router, and serving run scales. · `configs/retrieval_config.yaml`
- **Checkpoints**: model artifacts · Persisted retrieval, router, and TinyGPT weights and tokenizers.

### Retrieval Stack

- [BM25 Candidates](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/bm25.py): lexical retriever · `src/retrieval/bm25.py`
- [Bi-Encoder](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/bi_encoder.py): dense retriever · Shared Transformer encoder for query and document vectors. · `src/retrieval/bi_encoder.py`
- [Vector Store](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/vector_store.py): dense index · `src/retrieval/vector_store.py`
- [Cross-Encoder](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/cross_encoder.py): reranker · `src/retrieval/cross_encoder.py`
- [Retrieval Pipeline](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/retrieval/pipeline.py): hybrid RAG pipeline · Combines lexical and dense candidates before reranking. · `src/retrieval/pipeline.py`
- [Retrieval Training](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_retrieval_stack.py): training entry point · Trains encoders, mines negatives, and evaluates retrieval. · `src/train_retrieval_stack.py`

### Routing & Adaptation

- [Tool Registry](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/tools.py): tool definitions · Defines routable capabilities. · `src/router/tools.py`
- [Semantic Router](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/semantic_router.py): multi-label classifier · Maps queries to one or more registered tools. · `src/router/semantic_router.py`
- [QLoRA Router Adaptation](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/peft/finetune_router.py): PEFT trainer · Freezes or quantizes the base model and trains low-rank adapters. · `src/peft/finetune_router.py`
- [Router Training](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/train_router.py): training entry point · `src/train_router.py`
- [Router Judge](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/router/llm_judge.py): validation boundary · Uses Claude when configured, otherwise a deterministic local judge. · `src/router/llm_judge.py`

### Serving & Agent Runtime

- [Agent Loop](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/agent_loop.py): integration runtime · Routes tasks, invokes RAG when needed, and executes selected tools. · `src/serving/agent_loop.py`
- [TinyGPT Runtime](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/tiny_transformer.py): causal generation runtime · Supports explicit KV-cache-aware generation. · `src/serving/tiny_transformer.py`
- [KV Cache Benchmark](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/run_kv_cache_benchmark.py): performance benchmark · `src/serving/run_kv_cache_benchmark.py`
- [Speculative Decoding](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/serving/speculative_decoding.py): draft-target optimization · Verifies target-equivalent output and benchmarks decoding. · `src/serving/speculative_decoding.py`

### Evaluation & Outputs

- [Evaluation Metrics](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/src/eval/metrics.py): evaluation library · Shared retrieval, routing, adaptation, and serving measurements. · `src/eval/metrics.py`
- **JSON Results**: persisted outputs · Stage metrics and benchmark outputs.

### Other components

- [Full Pipeline](https://github.com/dhanuk8778-netizen/agentic-rag-tool-routing-/blob/main/scripts/run_full_pipeline.sh): orchestrator · Runs the local training and serving experiment stages. · `scripts/run_full_pipeline.sh`

## Connections

- 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
