Commit c66ca8e2 authored by Tero Ojanen's avatar Tero Ojanen
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

.env.example

0 → 100644
+71 −0
Changes for .env.example: 71 added lines, 0 removed lines.
Original line number Diff line number Diff line
# ============================================
# Aikamatka RAG - Environment Variables
# ============================================
# This file contains environment variables for all services.
# Copy this file to .env and fill in your values.

# ============================================
# DAME-EKTOT Middleware
# ============================================
REAL_API_URL=http://open-webui:3003/api/chat/completions
REAL_API_KEY=sk-dame-etkot
PUBLIC_API_URL=http://localhost:5003
CAPTURE_RESPONSES=true
LOG_LEVEL=INFO

# ============================================
# Open WebUI (docker image: openwebui/ollama:6.25)
# ============================================

# LLM Configuration - using vLLM via OpenAI API
OPENAI_API_BASE_URL=http://vllm-llm:8000/v1
OPENAI_API_KEY=sk-dame-etkot

# RAG Configuration
RAG_EMBEDDING_MODEL=BAAI/bge-m3
RAG_RE_RANKING_MODEL=BAAI/bge-reranker-v2-m3

# Vector Database - Qdrant (Open WebUI Qdrant Settings)
VECTOR_DB=qdrant
QDRANT_URI=http://qdrant:6333
QDRANT_PREFER_GRPC=True
QDRANT_GRPC_PORT=6334
ENABLE_QDRANT_MULTITENANCY_MODE=True
QDRANT_TIMEOUT=20
QDRANT_HNSW_M=64
QDRANT_API_KEY=

# Open WebUI Configuration (defaults, often set via GUI)
ENABLE_SIGNUP=false
ENABLE_LOGIN=false
ENABLE_RAG_LOCAL_WEB_SCRAPE=false

# ============================================
# vLLM Configuration
# ============================================
# Models are configured at runtime via Open WebUI GUI
# LLM Model: Gemma3-27B-it
# Embedding Model: BAAI/bge-m3
# Reranking Model: BAAI/bge-reranker-v2-m3

# ============================================
# Qdrant Configuration
# ============================================
QDRANT_API_KEY=

# ============================================
# Hugging Face Token (Optional - for private models)
# ============================================
HUGGING_FACE_HUB_TOKEN=

# ============================================
# vLLM Configuration (Optional - for RAG stack)
# ============================================
# To enable vLLM for Gemma3-27B-it (LLM): set to true
ENABLE_VLLM_LLM=false

# To enable GPU for embedding model: set to true
USE_EMBEDDING_GPU=false

# To enable GPU for reranker model: set to true
USE_RERANKER_GPU=false

.gitignore

0 → 100644
+40 −0
Changes for .gitignore: 40 added lines, 0 removed lines.
Original line number Diff line number Diff line
# General
.DS_Store
.idea/
.vscode/
*.swp
*.log

# Node / JS / Next.js
node_modules/
.next/
dist/
build/
coverage/
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
**/venv/
**/__pycache__/
env/
venv/
.env
.pytest_cache/
htmlcov/
site/

# Project Specific
response_logs/
**/testi/

AGENTS.md

0 → 100644
+229 −0
Changes for AGENTS.md: 229 added lines, 0 removed lines.
Original line number Diff line number Diff line
# AGENTS.md

This file provides instructions for AI coding agents working on the ETKOT & DAME RAG Project.

## Project Overview

This is a **Proof of Concept (PoC)** for the South Savo Open Cultural Heritage Pilot, developed in 2024–2025 in collaboration with Disec Oy, Business Archives ELKA, National Library of Finland, and National Archives of Finland.

The pilot was carried out under two European Union co-funded projects:

- **DAME** – South Savo Data Economy Accelerator: Shared Data as a Joint Success Factor
- **ETKOT** – South Savo Trained AI in Memory Lab

### RAG System Architecture

The system consists of:
- Two Next.js frontends (Aikamatka and Etkot Botti)
- A unified Python middleware layer
- Open WebUI 6.25 with RAG capabilities
- Qdrant vector database
- Optional vLLM for LLM inference with BAAI models

### Base LLM

**Google Gemma 3** acts as a rule-guided answer composer over retrieved content from curated cultural heritage sources.

## Data Sources (Pilot)

| Source | Description |
|--------|-------------|
| National Library of Finland | South Savo newspapers (1917–1923) |
| Business Archives ELKA | Archival histories |
| Suur-Savon Sähkö | Annual reports |

## Build and Test Commands

### Docker (Recommended)

```bash
# Start all services
docker compose up -d

# Stop services
docker compose down

# View logs
docker compose logs -f <service>

# Restart specific service
docker compose restart <service>
```

### Frontend Development

```bash
# Aikamatka UI (port 3000)
cd Aikamatka-develop
pnpm install
pnpm dev

# Etkot Botti UI (port 3001)
cd etkotbotti-main
pnpm install
pnpm dev
```

### Backend Development

```bash
# rag-middleware (port 5003)
cd rag-middleware/dame-etkot-unified-middleware
pip install -r requirements.txt
uvicorn main:app --reload --host 0.0.0.0 --port 5003
```

## Code Style

### TypeScript/JavaScript

- Use TypeScript with strict mode enabled
- Follow Next.js 14 App Router conventions
- Use ESLint with the project's configuration
- Prefer functional components with hooks

### Python

- Use Python 3.11 or later
- Follow PEP 8 style guidelines
- Use type hints
- Follow FastAPI best practices for the middleware

## Environment Variables

Create a `.env` file in the project root with:

```env
# Open WebUI Settings
ENABLE_SIGNUP=false
ENABLE_LOGIN=false

# vLLM Settings
HUGGING_FACE_HUB_TOKEN=

# RAG Settings
RAG_EMBEDDING_MODEL=BAAI/bge-m3
RAG_RE_RANKING_MODEL=BAAI/bge-reranker-v2-m3
QDRANT_URI=http://qdrant:6333

# Middleware Settings
REAL_API_URL=http://open-webui:3003/api/chat/completions
REAL_API_KEY=sk-dame-etkot
PUBLIC_API_URL=http://localhost:5003
```

See `.env.example` for a complete reference.

## Testing

```bash
# Run linting
pnpm lint

# Run type checking
pnpm type-check

# Run tests (when available)
pnpm test
```

## Git Workflow

### Basic Commands (Using Docker Compose Environment)

```bash
# View status
git status

# Add files to staging
git add <file>

# Commit changes with descriptive message
git commit -m "description of changes"

# Push to remote repository
git push origin main
```

### Commit Message Guidelines

- Use concise and descriptive messages
- Format: `type: brief description` (e.g., `docs: Update README.md`, `fix: Correct model name`)
- Use present tense (e.g., "Add feature" not "Added feature")

### Branch Naming

- `feature/your-feature-name` - For new features
- `bugfix/issue-description` - For bug fixes
- `docs/what-is-changed` - For documentation updates
- `refactor/what-is-refactored` - For code refactoring

### Best Practices

- Run linting and tests before committing
- Keep PRs focused on a single feature or fix
- Review changes before pushing to remote
- Use `docker compose` instead of `docker-compose` in all documentation
- Test Docker commands locally before committing documentation changes

### Common Tasks

#### Adding New Documentation Files

```bash
# 1. Create/update the file
# 2. Stage the changes
git add <file>

# 3. Commit with clear description
git commit -m "docs: Add documentation for <feature>"

# 4. Push to remote
git push origin main
```

#### Updating Docker Compose Documentation

When updating documentation that references Docker:

```bash
# Always use modern docker compose syntax
docker compose up -d      # Start services
docker compose down       # Stop services
docker compose logs -f    # View logs
docker compose restart    # Restart services
```

## Security Considerations

- Never commit `.env` files with real credentials
- Use `.env.example` as a template
- Rotate API keys if they are exposed
- Keep dependencies updated

## Architecture Files

- `ARCHITECTURE.md` - System architecture details
- `RAG_SETUP.md` - RAG stack setup guide
- `README.md` - Project overview and quick start

## RAG Process

The RAG system works in two phases:

### 1. Data Ingestion
1. Materials are collected from curated sources (National Library, Business Archives, Suur-Savon Sähkö)
2. Files are uploaded to Open WebUI
3. OWUI chunks documents and generates embeddings using BAAI models
4. Embeddings are stored in Qdrant vector database
5. Documents are indexed for semantic search

### 2. Query Processing
1. User asks a question through the interface
2. Middleware receives the query and forwards to Open WebUI
3. OWUI generates a query embedding using BAAI model
4. Qdrant retrieves relevant documents based on similarity
5. LLM (Gemma3-27B-it) composes an answer grounded in retrieved documents
6. Response flows back through middleware to UI

This approach reduces hallucinations by constraining responses to available source materials.
 No newline at end of file

ARCHITECTURE.md

0 → 100644
+200 −0
Changes for ARCHITECTURE.md: 200 added lines, 0 removed lines.
Original line number Diff line number Diff line
# System Architecture

## Overview

This is a **Proof of Concept (PoC)** for the South Savo Open Cultural Heritage Pilot, developed in 2024–2025 in collaboration with Disec Oy, Business Archives ELKA, National Library of Finland, and National Archives of Finland.

The pilot was carried out under two European Union co-funded projects:

- **DAME** – South Savo Data Economy Accelerator: Shared Data as a Joint Success Factor
- **ETKOT** – South Savo Trained AI in Memory Lab

### RAG Architecture

The system consists of:
- Two Next.js frontends (`Aikamatka` and `Etkot Botti`)
- A unified Python-based middleware layer (`dame-etkot-unified-middleware`)
- Open WebUI 6.25 with RAG capabilities
- Qdrant vector database
- Optional vLLM with BAAI models

### Base LLM

**Google Gemma 3** acts as a rule-guided answer composer over retrieved content from curated cultural heritage sources.

## API Flow Chart (Request Flow)

```mermaid
graph TD
    User[Browser/User] -->|Interacts| AikamatkaUI[Aikamatka UI :3000]
    User -->|Interacts| EtkotBottiUI[Etkot Botti UI :3001]
    
    AikamatkaUI -->|fetch NEXT_PUBLIC_API_URL/query| Middleware[rag-middleware :5003]
    EtkotBottiUI -->|fetch NEXT_PUBLIC_API_URL/query| Middleware
    
    subgraph "RAG Middleware Layer"
        Middleware -->|POST /query| MiddlewareLogic[Core Logic]
        MiddlewareLogic -->|Standardize| Proxy[Proxy Layer]
        Proxy -->|Call OWUI API| OpenWebUI[Open WebUI :3003]
    end
    
    subgraph "Open WebUI RAG Stack"
        OpenWebUI -->|LLM Inference| vLLM[vLLM :8000]
        OpenWebUI -->|Embedding/Reranking| vLLM
        OpenWebUI -->|Vector Search| Qdrant[Qdrant :6333]
    end
    
    MiddlewareLogic -->|UI-Compatible JSON| AikamatkaUI
    MiddlewareLogic -->|UI-Compatible JSON| EtkotBottiUI
```

## Data Workflow (Ingestion Flow)

```mermaid
graph LR
    subgraph "Data Collection"
        Digi[digidownload-cli] -->|Text Files| Upload1
        Finna[finna_fetcher] -->|JSON Metadata| Upload2
    end
    
    subgraph "Open WebUI Processing"
        Upload1 -->|Upload to OWUI| OWUI[Open WebUI :3003]
        Upload2 -->|Upload to OWUI| OWUI
        OWUI -->|Chunk Documents| Chunk
        Chunk -->|Generate Embeddings| Embed[Embedding Model]
        Embed -->|Store in Qdrant| Qdrant
        Chunk -->|Index for Search| Qdrant
    end
    
    subgraph "RAG at Runtime"
        Qdrant -->|Retrieve Documents| OpenWebUI
        Embed -->|Generate Query Embeddings| OpenWebUI
    end
```

## Data Sources (Pilot)

| Source | Description |
|--------|-------------|
| National Library of Finland | South Savo newspapers (1917–1923) |
| Business Archives ELKA | Archival histories |
| Suur-Savon Sähkö | Annual reports |

## Components

### Frontends

1.  **Aikamatka UI**:
    *   **Stack**: Next.js (App Router), TypeScript, React Bootstrap
    *   **Config**: `NEXT_PUBLIC_API_URL` (Build-time)
    *   **Port**: 3000 (Docker)
    *   **Features**: Multiple bots with buttons/input modes

2.  **Etkot Botti UI**:
    *   **Stack**: Next.js, TypeScript, React Bootstrap
    *   **Config**: `NEXT_PUBLIC_API_URL` (Build-time)
    *   **Port**: 3001 (Docker)
    *   **Features**: Single chat interface

3.  **digidownload-cli**:
    *   **Purpose**: Download text from National Library Digi service
    *   **Features**: Text-only downloads, configurable workers, OCR formats

4.  **finna_fetcher**:
    *   **Purpose**: Collect metadata from Finna search API
    *   **Features**: Metadata collection, filtering options

### Middleware

**`dame-etkot-unified-middleware`** is the single active backend service.

*   **Technology**: FastAPI + Uvicorn
*   **Endpoints**:
    *   `POST /query`: Legacy UI requests (clean JSON response)
    *   `POST /api/chat/completions`: OpenAI-compatible interface
    *   `GET /health`: Health check
*   **Features**:
    *   Upstream Proxying (OpenAI-compatible)
    *   Response Standardization
    *   Citation Normalization
    *   File Logging (optional)
    *   Gradio Explorer at `/explorer`

### Open WebUI 6.25

The main RAG interface with multiple bot support.

*   **Features**:
    *   Multiple bots with different knowledge bases
    *   RAG configuration per bot
    *   Document upload and indexing
    *   BAAI embedding model integration
    *   BAAI reranker integration
    *   Qdrant vector database support

### vLLM (Optional)

Runs the LLM and BAAI models.

*   **Models**:
    *   **Gemma3-27B-it**: Primary LLM for chat
    *   **BAAI/bge-m3**: Embedding model (Production used)
    *   **BAAI/bge-reranker-v2-m3**: Reranker model (Production used)
*   **API**: OpenAI-compatible

### Qdrant

Vector database for storing embeddings.

*   **Features**:
    *   Fast similarity search
    *   Filter-based queries
    *   Hybrid search support
    *   REST API

## RAG Process

The RAG system works in two phases:

### 1. Data Ingestion
1. Materials are collected from:
   - National Library of Finland (South Savo newspapers 1917–1923)
   - Business Archives ELKA (archival histories)
   - Suur-Savon Sähkö (annual reports)
2. Files are uploaded to Open WebUI
3. OWUI chunks documents and generates embeddings using BAAI models
4. Embeddings are stored in Qdrant vector database
5. Documents are indexed for semantic search

### 2. Query Processing
1. User asks a question through the interface
2. Middleware receives the query and forwards to Open WebUI
3. OWUI generates a query embedding using BAAI model
4. Qdrant retrieves relevant documents based on similarity
5. LLM (Gemma3-27B-it) composes an answer grounded in retrieved documents
6. Response flows back through middleware to UI

This approach reduces hallucinations by constraining responses to available source materials.

## Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `NEXT_PUBLIC_API_URL` | Middleware URL for UIs | http://localhost:5003 |
| `REAL_API_URL` | OWUI API URL | http://open-webui:3003/api/chat/completions |
| `OPENAI_API_BASE_URL` | vLLM OpenAI URL | http://vllm-llm:8000/v1 |
| `RAG_EMBEDDING_MODEL` | BAAI embedding model | BAAI/bge-m3 |
| `RAG_RE_RANKING_MODEL` | BAAI reranker model | BAAI/bge-reranker-v2-m3 |
| `QDRANT_URI` | Qdrant URL | http://qdrant:6333 |

## Ports

| Port | Service | Purpose |
|------|---------|---------|
| 3000 | Aikamatka UI | Main interface |
| 3001 | Etkobotti UI | Etkot interface |
| 3003 | Open WebUI | RAG interface |
| 5003 | rag-middleware | API gateway |
| 6333 | Qdrant | Vector database |
| 8000 | vLLM | LLM + BAAI models (optional) |
| 7860 | Gradio | Debug/Testing |
 No newline at end of file
+2 −0
Changes for Aikamatka-develop/.env.example: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
PORT=3000
NEXT_PUBLIC_API_URL=http://api.example
 No newline at end of file
Loading