Skip to content

About

Multi-user RAG knowledge platform with hybrid retrieval, cross-encoder reranking, checkable source citations, and per-query cost tracking

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

HamiKnowledge

CI Quality Gate Release Python Citation Validity Adversarial Benchmark License

HamiKnowledge is a local RAG demo for asking questions about English, Persian, and mixed-language technical documents, with source citations, abstention, and per-query cost accounting.

Run one API process in a trusted environment with demo documents. The API has no user authentication. Workspaces, documents, indexes, cache, and budgets live in process memory and reset on restart. Keep the API off public networks.


Architecture Overview

flowchart TD
    User["User / Client (RTL & LTR)"] -->|HTTP / Web Dashboard| API["FastAPI Gateway (/v1)"]
    
    subgraph Query State
        Scope["Workspace Scope Check"]
        Ledger["In-Memory Budget Ledger"]
        Cache["Workspace-Scoped Query Cache"]
    end
    
    API --> Scope
    Scope --> Ledger
    Ledger --> Cache
    
    subgraph Data Lifecycle & Ingestion
        Ingest["Ingestion Service (10MB Limit, MIME, UTF-8)"]
        Chunker["Heading-Aware Chunker (Offset Preservation)"]
        DenseEmbed["Deterministic Embeddings"]
        Store["In-Memory Store"]
    end
    
    API --> Ingest
    Ingest --> Chunker
    Chunker --> DenseEmbed
    DenseEmbed --> Store
    
    subgraph Retrieval & Synthesis Pipeline
        Lex["B0: Lexical Search"]
        Vec["B1: Dense Vector Cosine"]
        Fuser["B2: Reciprocal Rank Fusion (Default)"]
        Rerank["B3: Demo Reranker"]
        Generator["Deterministic & Grounded Generator"]
        Citations["Structural Citation Validator & Abstention"]
    end
    
    Cache -->|Cache Miss| Lex & Vec
    Store --> Lex & Vec
    Lex & Vec --> Fuser
    Fuser --> Rerank
    Rerank --> Generator
    Generator --> Citations
    Citations -->|Reconcile Spend| Ledger
    Citations -->|Cited Answer + Usage + Excerpts| User

    subgraph Bounded Read-Only Agent (R4)
        Agent["Bounded Agent Loop"]
        T1["search_documents"]
        T2["get_document_excerpt"]
    end
    API -.->|Agent Mode| Agent
    Agent --> T1 & T2
Loading

Key Features & Invariants

  • Workspace Scope: Retrieval, document lookups, query caching, and budget accounting are scoped by workspace ID. API clients can access any workspace on the instance.
  • Traceable Source Citations: Every claim links to an exact character offset (start_char to end_char) and heading path. Cited chunk IDs are structurally validated against retrieved context before response delivery.
  • Calibrated Abstention: When evidence is insufficient or contradictory, the system declines to hallucinate and provides an explicit abstention with unverified passages.
  • Document Handling: The demo generator reads retrieved text to assemble cited answers. The dashboard displays document and answer text without interpreting it as HTML.
  • Bounded Read-Only Agent: Permits exactly two safe tools (search_documents and get_document_excerpt), with a hard ceiling of 3 calls, a 20-second deadline, per-request budget reservations, and loop termination. Zero shell execution, zero arbitrary URLs, zero write tools.
  • Atomic Budget Ledger: Thread-safe ledger that atomically reserves conservative cost ceilings before external execution and reconciles actual token usage afterward, preventing overages even under concurrent load.
  • RTL-Correct UI: Native right-to-left layout for Persian documentation and mixed Latin technical terms using logical CSS properties (margin-inline-start, padding-inline, text-align: start).

Empirical Benchmark & Quality Results

The tables below summarize the recorded evaluation runs. The local dashboard uses deterministic adapters for offline operation.

1. Frozen Test Set Comparison (100 Items, 6,550 Chunks)

Evaluated against the frozen 100-item test split (70 answerable, 30 unanswerable; 30 English, 30 Persian, 40 mixed-language) on the Kubernetes v1 corpus (601 documents, 6,550 chunks):

Variant Strategy Recall@10 nDCG@10 MRR Cit. Validity p95 Latency Avg Cost/Query
B0 Pure Lexical (PostgreSQL FTS) 0.3857 0.2852 0.2555 100.0% 478.62 ms $0.000167
B1 Pure Vector (Dense Cosine) 0.0929 0.0651 0.0571 100.0% 677.66 ms $0.000194
B2 Hybrid RRF (Lexical + Vector) 0.3500 0.2338 0.1893 100.0% 1093.24 ms $0.000194
B3 Hybrid RRF + Cross-Encoder 0.3500 0.3028 0.2871 100.0% 1127.95 ms $0.000215
  • Default Selection: B2 (Hybrid RRF) is the recommended baseline balance of recall and predictable latency.
  • High-Precision Option: B3 (Hybrid RRF + Reranker) provides a +0.069 nDCG@10 uplift for applications prioritizing ranking precision over 34 ms of latency.
  • Full Report: evals/reports/release-report.json

2. Adversarial & Lifecycle Benchmark (40 Items)

Evaluated with python -m evals.adversarial across 5 threat categories:

Category Items Passed Pass Rate Key Invariant Enforced
Prompt Injection 12 12 100.0% Injections ignored; zero prompt leaks or fake tokens
Misleading Citations 8 8 100.0% False fixture claims rejected; authentic docs cited
Deleted Content 8 8 100.0% Immediate exclusion; queries abstain with 0 citations
ACL Changes 6 6 100.0% Server-side boundaries enforced; restricted content excluded
Tool Misuse 6 6 100.0% Shell/network requests blocked; max 3 tool calls enforced
Total 40 40 100.0% Full report: evals/reports/adversarial-report.json

Visual Tour & Live Verification

1. HamiKnowledge RAG Studio & Citation Inspector

The Persian dashboard supports workspace document indexing, citation inspection, abstention, and budget accounting.

HamiKnowledge Interactive RAG Studio

2. HamiCloud Demo

The screenshot shows a previous HamiCloud demo. The deployment script submits the HTTP API image to a private HamiCloud installation.

HamiCloud Operator Console


Interactive Demo Walkthrough (4-Minute Evaluation)

To observe and evaluate all key capabilities in order:

Time Demonstration Step Expected Evidence
0:00–0:50 Create a workspace and upload a Markdown document in the dashboard The document appears in the workspace list.
0:50–1:40 Ask an English or Persian question (e.g. What does the phase of a Pod represent?) Grounded answer with clickable [chk_...] citation pills opening source excerpts at exact character offsets.
1:40–2:15 Ask an unanswerable question (e.g. How to configure quantum warp drives on Kubernetes?) Explicit calibrated abstention badge; zero hallucinated claims or citations.
2:15–2:50 Switch workspace or delete a document and re-query Immediate revocation; document disappears from search candidates, cache is invalidated, and query abstains.
2:50–3:30 Compare B0, B1, B2, and B3 variants Observe latency, token count, and per-query cost breakdown in the ledger metrics bar.
3:30–4:00 Enable Bounded Agent mode and submit a query Observe strictly bounded read-only tool calls (max 3), redacted arguments, execution timings, and stop reasons.

Models & Cost Accounting

Pinned Model Revisions

  • Multilingual Embeddings: intfloat/multilingual-e5-small (384 dimensions, MIT License).
  • Cross-Encoder Reranker: cross-encoder/ms-marco-MiniLM-L-6-v2 (Apache-2.0 License).
  • Generation: Configurable provider with deterministic offline adapter for reproducible zero-network testing.

Price Table & Financial Safeguards

  • Prompt Tokens: $0.15 per 1,000,000 tokens ($0.00000015 / token).
  • Completion Tokens: $0.60 per 1,000,000 tokens ($0.00000060 / token).
  • Reservation Ceiling: Conservative $0.001 atomically reserved before each external call; reconciled to actual spend afterward.
  • Concurrent Budget Enforcement: Stress-tested with 20 parallel threads against a tight budget; zero unreserved calls and zero overdraft.

Architectural Decisions & Tradeoffs

  1. Process-Local Storage: The demo runs without a database, queue, or object store. PostgreSQL FTS and pgvector query builders are available as reference code.
  2. Strictly Bounded Read-Only Agent vs. Open-Ended Agentic Frameworks:
    • Decision: Exactly two read-only tools (search_documents and get_document_excerpt) with a 3-call hard ceiling and 20s deadline.
    • Rationale: Prevents infinite loops, runaway inference costs, prompt injection exfiltration, and unauthorized writes. Treats retrieved document content as passive text data rather than executable instructions.

Quickstart

Prerequisites

  • Python 3.12+ or Docker with Compose

1. Local Development Setup

# Clone repository
git clone https://github.com/hami9/HamiKnowledge.git
cd HamiKnowledge

# Create virtual environment & install dependencies
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install torch --index-url https://download.pytorch.org/whl/cpu
.\.venv\Scripts\python.exe -m pip install -e ".[models,dev]"

# Fetch and verify evaluation corpus
.\.venv\Scripts\python.exe -m evals.corpus fetch evals/datasets/corpus/k8s-docs-v1.yaml
.\.venv\Scripts\python.exe -m evals.corpus verify evals/datasets/corpus/k8s-docs-v1.yaml

# Run tests
.\.venv\Scripts\pytest -q

2. Start API Server & Web Dashboard

.\.venv\Scripts\uvicorn apps.api.main:app --host 127.0.0.1 --port 8000

Open your browser at http://localhost:8000/ to access the interactive RTL dashboard.

3. Docker Compose Deployment

docker compose -f deploy/docker-compose.yml up --build --remove-orphans -d

The dashboard and API share the same origin at http://127.0.0.1:8000/. Set HAMIKNOWLEDGE_PORT to use a different local port.

When upgrading an existing Compose demo, use the same project name so --remove-orphans removes its old database, cache, and object-store containers. Back up any data you stored in those services separately before upgrading.

4. Private HamiCloud Demo

Use an isolated HamiCloud 1.0.1 installation with private ingress. Build the API image with deploy/Dockerfile.api and publish it to a registry reachable and allowed by your HamiCloud installation.

Set HAMICLOUD_API_URL, HAMICLOUD_WORKSPACE_ID for an existing workspace, HAMICLOUD_SERVICE_TOKEN to an OIDC bearer token with deployment access, and HAMIKNOWLEDGE_API_IMAGE to your image reference. Then submit the release from the repository root.

python scripts/deploy_to_hamicloud.py

Check the returned operation ID in HamiCloud to confirm the rollout. Supply --idempotency-key on the first attempt and reuse that key for retries of the same submission.


Verification & Quality Gates

Run all automated quality gates:

# Lint check (0 errors)
.\.venv\Scripts\ruff check .

# Strict type check
.\.venv\Scripts\mypy evals ingestion retrieval apps db agent scripts tests

# Unit and integration tests
.\.venv\Scripts\pytest

# Dataset split validation (Strict)
.\.venv\Scripts\python -m evals.validate check --strict

# Automated CI regression gate
.\.venv\Scripts\python -m evals.regression

# Full 40-item adversarial benchmark (100% pass)
.\.venv\Scripts\python -m evals.adversarial

Repository Structure

HamiKnowledge/
├── apps/
│   ├── api/                 # FastAPI application, routers (query, agent, documents, budget)
│   └── web/                 # RTL-correct interactive web dashboard (index.html)
├── agent/                   # Bounded read-only agent loop, tool limits, trace audit
├── db/                      # In-memory store, budget ledger, multi-tenant query cache
├── deploy/                  # Docker Compose, Dockerfiles, HamiCloud application descriptor
├── docs/
│   ├── evidence/            # Milestone evidence records (A0, A1, A2, A3, A4, A5)
│   ├── evaluation-plan.md   # Evaluation methodology and metrics definition
│   ├── evaluation-rubric.md # Groundedness and citation scoring rubrics
│   └── model-selection.md   # Model benchmarks and licensing documentation
├── evals/
│   ├── datasets/            # dev.jsonl, test.jsonl, adversarial.jsonl, corpus lock
│   ├── reports/             # ablation-report.json, release-report.json, adversarial-report.json
│   ├── ablation.py          # B0-B3 ablation runner
│   ├── adversarial.py       # 40-item adversarial test harness
│   └── regression.py        # Automated CI regression gate
├── ingestion/               # Heading-aware chunker, text normalizer, lifecycle service
├── retrieval/               # Lexical FTS, dense vector, RRF fusion, reranker, generation
└── tests/                   # 61 comprehensive unit, integration, concurrency & safety tests

Documentation & Evidence Records


Attribution & License

  • Evaluation Corpus: Kubernetes documentation, (c) The Kubernetes Authors, CC BY 4.0. Source text is not redistributed in this repository.
  • License: MIT License. See LICENSE for details.

About

Multi-user RAG knowledge platform with hybrid retrieval, cross-encoder reranking, checkable source citations, and per-query cost tracking

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages