Skip to content

Repository files navigation

🧠 Watsonx RAG Knowledge Base

Python IBM Watsonx LangChain FastAPI Streamlit License: MIT CI

Português | English


Português

Descrição

Sistema de Base de Conhecimento Empresarial com RAG (Retrieval-Augmented Generation) alimentado por IBM Watsonx AI e modelos Granite. O sistema permite que empresas façam perguntas sobre seus documentos internos e recebam respostas precisas com citação de fontes, verificação de alucinações e trilha de auditoria completa via watsonx.governance.

Características Principais

Feature Descrição
📄 Ingestão Multi-formato PDF, Markdown, DOCX, HTML, TXT com extração de metadados
🔍 Busca Híbrida Dense vector (Slate embeddings) + Sparse BM25 com Reciprocal Rank Fusion
🤖 Geração com Granite IBM Granite-13b-chat-v2 com citação automática de fontes
🛡️ Guardrails Detecção de alucinações, filtro de injeção de prompt, verificação de grounding
📊 Governança Logging de interações, score de factualidade, trilha de auditoria (watsonx.governance)
💬 Interface Chat Streamlit com histórico de conversas, fontes e score de confiança
🐳 Docker Ready Docker Compose com ChromaDB, FastAPI e Streamlit
✅ Testado pytest com cobertura > 80%

Arquitetura

flowchart TD
    subgraph Ingestion["📄 Ingestão de Documentos"]
        A[Documentos PDF/MD/DOCX/HTML] --> B[Document Loader]
        B --> C[Chunker: RecursiveTextSplitter]
        C --> D[Slate-125m Embeddings via watsonx.ai]
        D --> E[(ChromaDB Vector Store)]
    end

    subgraph Retrieval["🔍 Retrieval Híbrido"]
        F[Query do Usuário] --> G[Query Embedding: Slate-125m]
        G --> H[Dense Search: Top-K Similarity]
        E --> H
        F --> I[BM25 Sparse Search]
        E --> I
        H --> J[Reciprocal Rank Fusion]
        I --> J
    end

    subgraph Generation["🤖 Geração"]
        J --> K[Context Assembly + Prompt Template]
        K --> L[Granite-13b-chat-v2 via watsonx.ai]
        L --> M[Guardrails: Grounding Check]
    end

    subgraph Governance["📊 Governança"]
        M --> N[watsonx.governance Logger]
        N --> O[Audit Trail + Factuality Score]
    end

    M --> P[Streamlit Chat UI]
    O --> Q[Governance Dashboard]
Loading

Stack Tecnológico

IBM Watsonx.ai          → Granite-13b-chat-v2 (geração) + Slate-125m (embeddings)
IBM Watsonx.governance   → Logging, factualidade, trilha de auditoria
LangChain + langchain-ibm → Orquestração RAG
ChromaDB                 → Vector store para embeddings
BM25 (rank_bm25)        → Retrieval esparso por keywords
FastAPI                  → API REST backend
Streamlit                → Interface de usuário
Docker Compose           → Orquestração de serviços
pytest + ruff + mypy     → Qualidade de código

Início Rápido

# 1. Clone o repositório
git clone https://github.com/galafis/watsonx-rag-knowledge-base.git
cd watsonx-rag-knowledge-base

# 2. Configure as variáveis de ambiente
cp .env.example .env
# Edite .env com suas credenciais IBM Watsonx

# 3. Inicie com Docker Compose
make docker-up

# 4. Acesse a interface
# UI: http://localhost:8501
# API: http://localhost:8080/docs

Desenvolvimento Local

# Instale dependências de desenvolvimento
make install-dev

# Execute linting
make lint

# Execute testes
make test-cov

# Inicie a API
make run-api

# Inicie a UI (em outro terminal)
make run-ui

Estrutura do Projeto

watsonx-rag-knowledge-base/
├── config/
│   └── settings.yaml          # Configuração de modelos e parâmetros
├── src/
│   ├── ingestion/
│   │   ├── loader.py          # Carregamento multi-formato de documentos
│   │   ├── chunker.py         # Divisão em chunks com overlap
│   │   └── embedder.py        # Embeddings via Watsonx Slate
│   ├── retrieval/
│   │   ├── vector_store.py    # ChromaDB vector store
│   │   └── hybrid_search.py   # Busca híbrida Dense + BM25 + RRF
│   ├── generation/
│   │   ├── chain.py           # Pipeline RAG completo
│   │   ├── guardrails.py      # Validação de input/output
│   │   └── prompt_templates.py # Templates de prompt
│   ├── governance/
│   │   └── logger.py          # Logging de governança e métricas
│   ├── api/
│   │   ├── routes.py          # Endpoints FastAPI
│   │   └── schemas.py         # Modelos Pydantic
│   └── ui/
│       └── app.py             # Interface Streamlit
├── tests/                     # Testes unitários e de integração
├── data/sample_docs/          # Documentos de exemplo
├── Dockerfile                 # Build multi-stage
├── docker-compose.yml         # Orquestração de serviços
├── Makefile                   # Comandos de desenvolvimento
└── pyproject.toml             # Configuração do projeto

API Endpoints

Método Rota Descrição
GET /health Health check do sistema
POST /query Consulta RAG com pergunta
POST /ingest Ingestão de documentos
GET /governance/metrics Métricas de governança
GET /documents/count Contagem de documentos

English

Description

Enterprise RAG (Retrieval-Augmented Generation) Knowledge Base powered by IBM Watsonx AI and Granite models. The system enables enterprises to ask questions about their internal documents and receive accurate answers with source citations, hallucination detection, and complete audit trails via watsonx.governance.

Key Features

Feature Description
📄 Multi-format Ingestion PDF, Markdown, DOCX, HTML, TXT with metadata extraction
🔍 Hybrid Search Dense vector (Slate embeddings) + Sparse BM25 with Reciprocal Rank Fusion
🤖 Granite Generation IBM Granite-13b-chat-v2 with automatic source citation
🛡️ Guardrails Hallucination detection, prompt injection filter, grounding verification
📊 Governance Interaction logging, factuality scoring, audit trail (watsonx.governance)
💬 Chat Interface Streamlit with conversation history, sources, and confidence scores
🐳 Docker Ready Docker Compose with ChromaDB, FastAPI, and Streamlit
✅ Tested pytest with > 80% coverage

Architecture

flowchart TD
    subgraph Ingestion["📄 Document Ingestion"]
        A[Documents PDF/MD/DOCX/HTML] --> B[Document Loader]
        B --> C[Chunker: RecursiveTextSplitter]
        C --> D[Slate-125m Embeddings via watsonx.ai]
        D --> E[(ChromaDB Vector Store)]
    end

    subgraph Retrieval["🔍 Hybrid Retrieval"]
        F[User Query] --> G[Query Embedding: Slate-125m]
        G --> H[Dense Search: Top-K Similarity]
        E --> H
        F --> I[BM25 Sparse Search]
        E --> I
        H --> J[Reciprocal Rank Fusion]
        I --> J
    end

    subgraph Generation["🤖 Generation"]
        J --> K[Context Assembly + Prompt Template]
        K --> L[Granite-13b-chat-v2 via watsonx.ai]
        L --> M[Guardrails: Grounding Check]
    end

    subgraph Governance["📊 Governance"]
        M --> N[watsonx.governance Logger]
        N --> O[Audit Trail + Factuality Score]
    end

    M --> P[Streamlit Chat UI]
    O --> Q[Governance Dashboard]
Loading

Quick Start

# 1. Clone the repository
git clone https://github.com/galafis/watsonx-rag-knowledge-base.git
cd watsonx-rag-knowledge-base

# 2. Configure environment variables
cp .env.example .env
# Edit .env with your IBM Watsonx credentials

# 3. Start with Docker Compose
make docker-up

# 4. Access the interface
# UI: http://localhost:8501
# API: http://localhost:8080/docs

Technology Stack

Component Technology Purpose
LLM IBM Granite-13b-chat-v2 Answer generation with source citation
Embeddings IBM Slate-125m-english-rtrvr Document and query embeddings
Vector Store ChromaDB Dense vector storage and similarity search
Sparse Search BM25 (rank_bm25) Keyword-based retrieval
Orchestration LangChain + langchain-ibm RAG pipeline orchestration
API FastAPI REST API backend
UI Streamlit Chat interface
Governance watsonx.governance Audit trails and quality monitoring
Infrastructure Docker Compose Service orchestration

Environment Variables

Variable Description Required
WATSONX_API_KEY IBM Cloud API key Yes
WATSONX_PROJECT_ID Watsonx project ID Yes
WATSONX_URL Watsonx API endpoint No (default: us-south)
CHROMA_HOST ChromaDB host No (default: localhost)
CHROMA_PORT ChromaDB port No (default: 8000)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Gabriel Demetrios Lafis - GitHub | LinkedIn

About

Enterprise RAG Knowledge Base powered by IBM Watsonx AI and Granite models with hybrid search, guardrails, and governance audit trails

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages