Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: rag-provider

Bingxi Zhaoc1752f051247
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 2d2cde558..fbbf2c44b 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -8,15 +8,15 @@ on:
# Trigger on version tags
push:
tags:
- - 'v*.*.*'
+ - "v*.*.*"
# Allow manual trigger
workflow_dispatch:
inputs:
tag:
- description: 'Docker image tag (e.g., latest, v0.2.0)'
+ description: "Docker image tag (e.g., latest, v0.2.0)"
required: false
- default: 'latest'
+ default: "latest"
env:
REGISTRY: ghcr.io
@@ -34,6 +34,9 @@ jobs:
contents: read
packages: write
+ outputs:
+ digest: ${{ steps.build.outputs.digest }}
+
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -77,6 +80,7 @@ jobs:
type=ref,event=tag
- name: Build and push AMD64 image
+ id: build
uses: docker/build-push-action@v6
with:
context: .
@@ -90,6 +94,7 @@ jobs:
cache-to: type=gha,mode=max,scope=amd64
build-args: |
BACKEND_PORT=8001
+ provenance: false
# ============================================
# Build ARM64 Image (Apple Silicon, ARM servers)
@@ -102,6 +107,9 @@ jobs:
contents: read
packages: write
+ outputs:
+ digest: ${{ steps.build.outputs.digest }}
+
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -148,6 +156,7 @@ jobs:
type=raw,value=${{ github.ref_name }}-arm64,enable=${{ startsWith(github.ref, 'refs/tags/') }}
- name: Build and push ARM64 image
+ id: build
uses: docker/build-push-action@v6
with:
context: .
@@ -161,6 +170,42 @@ jobs:
cache-to: type=gha,mode=max,scope=arm64
build-args: |
BACKEND_PORT=8001
+ provenance: false
+
+ # ============================================
+ # Create Multi-arch Manifest (optional)
+ # ============================================
+ create-manifest:
+ name: Create Multi-arch Manifest
+ runs-on: ubuntu-latest
+ needs: [build-amd64, build-arm64]
+ if: github.event_name == 'release'
+
+ permissions:
+ contents: read
+ packages: write
+
+ steps:
+ - name: Log in to Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ${{ env.REGISTRY }}
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Create and push multi-arch manifest
+ run: |
+ # Extract version from tag (e.g., v0.5.0 -> 0.5.0)
+ VERSION=${GITHUB_REF_NAME#v}
+
+ # Create manifest for version tag
+ docker manifest create ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-multi \
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION} \
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-arm64
+
+ docker manifest push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-multi
+
+ echo "โœ… Created multi-arch manifest: ${VERSION}-multi"
# ============================================
# Generate Summary
@@ -169,14 +214,22 @@ jobs:
name: Generate Summary
runs-on: ubuntu-latest
needs: [build-amd64, build-arm64]
+ if: always()
steps:
- name: Generate image summary
run: |
- echo "## ๐Ÿณ Docker Images Published" >> $GITHUB_STEP_SUMMARY
+ echo "## ๐Ÿณ Docker Images Build Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Registry:** \`${{ env.REGISTRY }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
+ echo "### Build Status" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Architecture | Status |" >> $GITHUB_STEP_SUMMARY
+ echo "|--------------|--------|" >> $GITHUB_STEP_SUMMARY
+ echo "| AMD64 | ${{ needs.build-amd64.result == 'success' && 'โœ… Success' || 'โŒ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| ARM64 | ${{ needs.build-arm64.result == 'success' && 'โœ… Success' || 'โŒ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
echo "### Available Images" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Architecture | Image Tag | Use Case |" >> $GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml
index 1ae50f868..2585a1f29 100644
--- a/.github/workflows/linting.yaml
+++ b/.github/workflows/linting.yaml
@@ -11,8 +11,11 @@ on:
- develop
jobs:
- lint-and-format:
- name: Linting and Formatting
+ # ============================================
+ # Python Linting with pre-commit
+ # ============================================
+ python-lint:
+ name: Python Linting
runs-on: ubuntu-latest
steps:
@@ -22,14 +25,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v5
with:
- python-version: '3.10'
-
- - name: Set up Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '20'
- cache: 'npm'
- cache-dependency-path: web/package-lock.json
+ python-version: "3.10"
- name: Cache pre-commit
uses: actions/cache@v4
@@ -39,19 +35,14 @@ jobs:
restore-keys: |
pre-commit-
- - name: Install Python dependencies
+ - name: Install pre-commit
run: |
python -m pip install --upgrade pip
pip install pre-commit
- - name: Install frontend dependencies
- working-directory: ./web
- run: npm ci
-
- - name: Run pre-commit
+ - name: Run pre-commit on Python files
run: |
- # Show which hooks will run
- echo "Running pre-commit hooks..."
+ echo "๐Ÿ” Running pre-commit hooks on Python files..."
pre-commit run --all-files --verbose 2>&1 || {
echo ""
echo "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—"
@@ -71,3 +62,84 @@ jobs:
echo ""
exit 1
}
+
+ # ============================================
+ # Frontend Linting (TypeScript/JavaScript)
+ # ============================================
+ frontend-lint:
+ name: Frontend Linting
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "20"
+ cache: "npm"
+ cache-dependency-path: web/package-lock.json
+
+ - name: Install frontend dependencies
+ working-directory: ./web
+ run: npm ci
+
+ - name: Run ESLint
+ working-directory: ./web
+ run: |
+ echo "๐Ÿ” Running ESLint on frontend code..."
+ npm run lint 2>&1 || {
+ echo ""
+ echo "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—"
+ echo "โ•‘ โŒ ESLint checks failed! โ•‘"
+ echo "โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ"
+ echo "โ•‘ Please run the following commands locally to fix linting issues: โ•‘"
+ echo "โ•‘ โ•‘"
+ echo "โ•‘ cd web โ•‘"
+ echo "โ•‘ npm run lint # Check for linting issues โ•‘"
+ echo "โ•‘ npm run lint -- --fix # Auto-fix linting issues โ•‘"
+ echo "โ•‘ โ•‘"
+ echo "โ•‘ Then commit and push the changes. โ•‘"
+ echo "โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•"
+ echo ""
+ exit 1
+ }
+
+ - name: TypeScript type check
+ working-directory: ./web
+ run: |
+ echo "๐Ÿ” Running TypeScript type check..."
+ npx tsc --noEmit 2>&1 || {
+ echo ""
+ echo "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—"
+ echo "โ•‘ โŒ TypeScript type check failed! โ•‘"
+ echo "โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ"
+ echo "โ•‘ Please fix the TypeScript errors shown above. โ•‘"
+ echo "โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•"
+ echo ""
+ exit 1
+ }
+
+ # ============================================
+ # Lint Summary
+ # ============================================
+ lint-summary:
+ name: Lint Summary
+ runs-on: ubuntu-latest
+ needs: [python-lint, frontend-lint]
+ if: always()
+
+ steps:
+ - name: Generate summary
+ run: |
+ echo "## ๐Ÿ” Linting Results" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
+ echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
+ echo "| Python (pre-commit) | ${{ needs.python-lint.result == 'success' && 'โœ… Passed' || 'โŒ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Frontend (ESLint + TypeScript) | ${{ needs.frontend-lint.result == 'success' && 'โœ… Passed' || 'โŒ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+
+ - name: Fail if linting failed
+ if: needs.python-lint.result == 'failure' || needs.frontend-lint.result == 'failure'
+ run: exit 1
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index cf492e4ce..75e7ac56f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -22,20 +22,33 @@ on:
- "pyproject.toml"
jobs:
- # Quick import check to ensure modules load correctly
- # Uses minimal dependencies to avoid disk space issues
+ # ============================================
+ # Import Check - Quick validation across Python versions
+ # ============================================
import-check:
- name: Import Check
+ name: Import Check (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11"]
steps:
- name: Checkout code
uses: actions/checkout@v6
- - name: Set up Python
+ - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
- python-version: "3.10"
+ python-version: ${{ matrix.python-version }}
+
+ - name: Cache pip packages
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-${{ matrix.python-version }}-
- name: Install minimal dependencies for import check
run: |
@@ -59,6 +72,7 @@ jobs:
- name: Check module imports
run: |
+ echo "๐Ÿ Testing with Python ${{ matrix.python-version }}"
python -c "from src.services.llm import complete, stream, fetch_models, sanitize_url; print('โœ… LLM service imports OK')"
python -c "from src.services.llm.config import get_llm_config; print('โœ… LLM config imports OK')"
python -c "from src.services.config.loader import load_config_with_main; print('โœ… Config loader imports OK')"
@@ -66,3 +80,82 @@ jobs:
python -c "from src.logging import get_logger; print('โœ… Logging imports OK')"
env:
PYTHONPATH: ${{ github.workspace }}
+
+ # ============================================
+ # Unit Tests - Run pytest across Python versions
+ # ============================================
+ unit-tests:
+ name: Unit Tests (Python ${{ matrix.python-version }})
+ runs-on: ubuntu-latest
+ needs: import-check
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11"]
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Cache pip packages
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-${{ matrix.python-version }}-
+
+ - name: Install test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install pytest pytest-asyncio pytest-cov
+ # Install minimal dependencies for testing
+ pip install \
+ python-dotenv>=1.0.0 \
+ PyYAML>=6.0 \
+ tiktoken>=0.5.0 \
+ jinja2>=3.1.0 \
+ requests>=2.32.2 \
+ openai>=1.30.0 \
+ aiohttp>=3.9.4 \
+ httpx>=0.27.0 \
+ nest_asyncio>=1.5.8 \
+ tenacity>=8.0.0 \
+ fastapi>=0.100.0 \
+ pydantic>=2.0.0 \
+ numpy>=1.24.0,\<2.0.0
+
+ - name: Run unit tests
+ run: |
+ echo "๐Ÿงช Running tests with Python ${{ matrix.python-version }}"
+ pytest tests/ -v --tb=short --ignore=tests/agents/ || echo "โš ๏ธ Some tests failed or no tests found"
+ env:
+ PYTHONPATH: ${{ github.workspace }}
+
+ # ============================================
+ # Test Summary
+ # ============================================
+ test-summary:
+ name: Test Summary
+ runs-on: ubuntu-latest
+ needs: [import-check, unit-tests]
+ if: always()
+
+ steps:
+ - name: Check test results
+ run: |
+ echo "## ๐Ÿงช Test Results Summary" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Python Version | Import Check | Unit Tests |" >> $GITHUB_STEP_SUMMARY
+ echo "|----------------|--------------|------------|" >> $GITHUB_STEP_SUMMARY
+ echo "| 3.10 | ${{ needs.import-check.result == 'success' && 'โœ…' || 'โŒ' }} | ${{ needs.unit-tests.result == 'success' && 'โœ…' || 'โŒ' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| 3.11 | ${{ needs.import-check.result == 'success' && 'โœ…' || 'โŒ' }} | ${{ needs.unit-tests.result == 'success' && 'โœ…' || 'โŒ' }} |" >> $GITHUB_STEP_SUMMARY
+
+ - name: Fail if tests failed
+ if: needs.import-check.result == 'failure' || needs.unit-tests.result == 'failure'
+ run: exit 1
diff --git a/.github/workflows/update-roster.yml b/.github/workflows/update-roster.yml
index fddadb68c..45fb3e8e6 100644
--- a/.github/workflows/update-roster.yml
+++ b/.github/workflows/update-roster.yml
@@ -1,9 +1,9 @@
name: Update Repo Roster
on:
- # Run twice a day (at 00:00 and 12:00 UTC)
+ # Run once a day (at 00:00 UTC)
schedule:
- - cron: '0 0,12 * * *'
+ - cron: '0 0 * * *'
# Allow manual trigger
workflow_dispatch:
# Run when stars/forks might change (on push to main)
diff --git a/config/main.yaml b/config/main.yaml
index 619523a19..6db5d8b5c 100644
--- a/config/main.yaml
+++ b/config/main.yaml
@@ -28,16 +28,15 @@ tools:
enabled: true
max_results: 5
logging:
+ # Global log level for the entire system (DEBUG, INFO, WARNING, ERROR)
+ # This controls both DeepTutor logs and RAG module logs
level: DEBUG
save_to_file: true
console_output: true
- lightrag_forwarding:
- enabled: true
- min_level: DEBUG
- add_prefix: true
- logger_names:
- knowledge_init: LightRAG-Init
- rag_tool: LightRAG
+ # RAG module logger name mapping (optional customization)
+ rag_logger_names:
+ knowledge_init: RAG-Init
+ rag_tool: RAG
question:
# Refactored: no iteration loops (max_rounds removed)
rag_query_count: 3
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 953f38be1..a8e5bca34 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -35,8 +35,7 @@ services:
environment:
- NODE_ENV=development
- # Enable more verbose logging in development
- - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-DEBUG}
+ # Logging: Configure in config/main.yaml -> logging.level
# In development, we might want to see logs directly
# Uncomment the following to disable log files and see everything in console
diff --git a/docker-compose.yml b/docker-compose.yml
index f05c788cc..b7a3c0bb9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -57,8 +57,7 @@ services:
# Web Search Configuration (Optional)
- SEARCH_PROVIDER=${SEARCH_PROVIDER:-perplexity}
- SEARCH_API_KEY=${SEARCH_API_KEY:-}
- # Logging Configuration
- - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-INFO}
+ # Logging: Configure in config/main.yaml -> logging.level
# ============================================
# Service Ports Configuration
# ============================================
diff --git a/requirements.txt b/requirements.txt
index 6047daedc..8ecf5e36e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -44,6 +44,7 @@ pydantic>=2.0.0
# ============================================
lightrag-hku>=1.0.0
raganything>=0.1.0
+docling>=2.31.0 # Document parser for Office/HTML (alternative to MinerU)
# ============================================
# LlamaIndex
diff --git a/scripts/check_install.py b/scripts/check_install.py
new file mode 100644
index 000000000..5680e9f46
--- /dev/null
+++ b/scripts/check_install.py
@@ -0,0 +1,461 @@
+#!/usr/bin/env python
+"""
+DeepTutor Installation Checker
+
+Verifies that all required dependencies are correctly installed.
+Run this script to diagnose installation issues.
+"""
+
+import importlib.metadata
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+# Set Windows console UTF-8 encoding
+if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
+
+
+# Color codes for terminal output
+class Colors:
+ RED = "\033[0;31m"
+ GREEN = "\033[0;32m"
+ YELLOW = "\033[1;33m"
+ BLUE = "\033[0;34m"
+ CYAN = "\033[0;36m"
+ NC = "\033[0m" # No Color
+
+ @classmethod
+ def disable(cls):
+ """Disable colors for non-TTY output"""
+ cls.RED = cls.GREEN = cls.YELLOW = cls.BLUE = cls.CYAN = cls.NC = ""
+
+
+# Disable colors if not a TTY
+if not sys.stdout.isatty():
+ Colors.disable()
+
+
+def print_header(message: str):
+ """Print section header"""
+ print(f"\n{'=' * 60}")
+ print(f"๐Ÿ“‹ {message}")
+ print("=" * 60)
+
+
+def print_success(message: str):
+ """Print success message"""
+ print(f"{Colors.GREEN}โœ… {message}{Colors.NC}")
+
+
+def print_error(message: str):
+ """Print error message"""
+ print(f"{Colors.RED}โŒ {message}{Colors.NC}")
+
+
+def print_warning(message: str):
+ """Print warning message"""
+ print(f"{Colors.YELLOW}โš ๏ธ {message}{Colors.NC}")
+
+
+def print_info(message: str):
+ """Print info message"""
+ print(f"{Colors.CYAN}โ„น๏ธ {message}{Colors.NC}")
+
+
+def get_package_version(package_name: str) -> str | None:
+ """Get installed package version"""
+ try:
+ return importlib.metadata.version(package_name)
+ except importlib.metadata.PackageNotFoundError:
+ return None
+
+
+def check_python_environment() -> bool:
+ """Check Python environment"""
+ print_header("Python Environment")
+
+ all_ok = True
+
+ # Python version
+ py_version = sys.version_info
+ print_info(f"Python version: {py_version.major}.{py_version.minor}.{py_version.micro}")
+
+ if py_version >= (3, 10):
+ print_success(f"Python {py_version.major}.{py_version.minor} meets requirement (>=3.10)")
+ else:
+ print_error(f"Python {py_version.major}.{py_version.minor} is below requirement (>=3.10)")
+ all_ok = False
+
+ # Python executable
+ print_info(f"Python executable: {sys.executable}")
+
+ # Virtual environment
+ in_venv = hasattr(sys, "real_prefix") or (
+ hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
+ )
+ conda_env = os.environ.get("CONDA_DEFAULT_ENV")
+
+ if conda_env:
+ print_success(f"Conda environment: {conda_env}")
+ elif in_venv:
+ print_success(f"Virtual environment: {sys.prefix}")
+ else:
+ print_warning("No isolated environment detected (recommended: use conda or venv)")
+
+ return all_ok
+
+
+def check_backend_packages() -> tuple[bool, int, int]:
+ """Check backend Python packages"""
+ print_header("Backend Dependencies")
+
+ # Required packages: (pip_name, import_name, min_version, is_optional)
+ packages = [
+ # Core
+ ("python-dotenv", "dotenv", "1.0.0", False),
+ ("PyYAML", "yaml", "6.0", False),
+ ("tiktoken", "tiktoken", "0.5.0", False),
+ ("jinja2", "jinja2", "3.1.0", False),
+ # HTTP & API
+ ("requests", "requests", "2.32.0", False),
+ ("openai", "openai", "1.30.0", False),
+ ("anthropic", "anthropic", "0.30.0", False),
+ ("aiohttp", "aiohttp", "3.9.0", False),
+ ("httpx", "httpx", "0.27.0", False),
+ # Async
+ ("nest-asyncio", "nest_asyncio", "1.5.8", False),
+ ("tenacity", "tenacity", "8.0.0", False),
+ # Web framework
+ ("fastapi", "fastapi", "0.100.0", False),
+ ("uvicorn", "uvicorn", "0.24.0", False),
+ ("websockets", "websockets", "12.0", False),
+ ("pydantic", "pydantic", "2.0.0", False),
+ # RAG
+ ("lightrag-hku", "lightrag", "1.0.0", False),
+ ("raganything", "raganything", "0.1.0", False),
+ ("llama-index", "llama_index", "0.14.0", False),
+ # Document parsing
+ ("docling", "docling", "2.31.0", True), # Optional
+ ("PyMuPDF", "fitz", "1.26.0", False),
+ # Academic
+ ("arxiv", "arxiv", "2.0.0", False),
+ # Optional API clients
+ ("perplexityai", "perplexity", "0.1.0", True),
+ ("dashscope", "dashscope", "1.14.0", True),
+ ]
+
+ installed = 0
+ missing = 0
+ all_ok = True
+
+ for pip_name, import_name, min_version, is_optional in packages:
+ try:
+ __import__(import_name)
+ version = get_package_version(pip_name)
+ version_str = f" (v{version})" if version else ""
+ print_success(f" โœ“ {pip_name}{version_str}")
+ installed += 1
+ except ImportError:
+ if is_optional:
+ print_warning(f" โš  {pip_name} not installed (optional)")
+ else:
+ print_error(f" โœ— {pip_name} not installed")
+ all_ok = False
+ missing += 1
+
+ return all_ok, installed, missing
+
+
+def check_frontend_packages(project_root: Path) -> tuple[bool, int, int]:
+ """Check frontend Node.js packages"""
+ print_header("Frontend Dependencies")
+
+ web_dir = project_root / "web"
+ node_modules = web_dir / "node_modules"
+ package_json = web_dir / "package.json"
+
+ installed = 0
+ missing = 0
+ all_ok = True
+
+ # Check npm
+ npm_path = shutil.which("npm")
+ if npm_path:
+ try:
+ result = subprocess.run(
+ ["npm", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ npm_version = result.stdout.strip()
+ print_success(f"npm available (v{npm_version})")
+ except Exception:
+ print_warning("npm found but version check failed")
+ else:
+ print_error("npm not found - Node.js is required for frontend")
+ all_ok = False
+
+ # Check node
+ node_path = shutil.which("node")
+ if node_path:
+ try:
+ result = subprocess.run(
+ ["node", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ node_version = result.stdout.strip()
+ print_success(f"Node.js available ({node_version})")
+ except Exception:
+ print_warning("Node.js found but version check failed")
+ else:
+ print_error("Node.js not found")
+ all_ok = False
+
+ # Check package.json exists
+ if not package_json.exists():
+ print_error(f"package.json not found: {package_json}")
+ return False, 0, 0
+
+ # Check node_modules
+ if not node_modules.exists():
+ print_error("node_modules directory does not exist")
+ print_info("Run 'npm install' in web/ directory to install dependencies")
+ return False, 0, 0
+
+ # Check key packages
+ key_packages = [
+ "next",
+ "react",
+ "react-dom",
+ "typescript",
+ "tailwindcss",
+ "@radix-ui/react-dialog",
+ "lucide-react",
+ ]
+
+ print_info("Checking key frontend packages...")
+
+ for pkg in key_packages:
+ pkg_dir = node_modules / pkg
+ if pkg_dir.exists():
+ # Try to get version from package.json
+ pkg_json = pkg_dir / "package.json"
+ version = ""
+ if pkg_json.exists():
+ try:
+ import json
+
+ with open(pkg_json) as f:
+ data = json.load(f)
+ version = f" (v{data.get('version', '?')})"
+ except Exception:
+ pass
+ print_success(f" โœ“ {pkg}{version}")
+ installed += 1
+ else:
+ print_error(f" โœ— {pkg} not installed")
+ missing += 1
+ all_ok = False
+
+ return all_ok, installed, missing
+
+
+def check_system_tools() -> bool:
+ """Check system tools and utilities"""
+ print_header("System Tools")
+
+ all_ok = True
+
+ # Git
+ git_path = shutil.which("git")
+ if git_path:
+ try:
+ result = subprocess.run(
+ ["git", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ git_version = result.stdout.strip()
+ print_success(f"{git_version}")
+ except Exception:
+ print_warning("git found but version check failed")
+ else:
+ print_warning("git not found (optional but recommended)")
+
+ # uv (fast Python package manager)
+ uv_path = shutil.which("uv")
+ if uv_path:
+ try:
+ result = subprocess.run(
+ ["uv", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ uv_version = result.stdout.strip()
+ print_success(f"uv available ({uv_version})")
+ except Exception:
+ print_warning("uv found but version check failed")
+ else:
+ print_info("uv not found (optional, for faster package installation)")
+
+ return all_ok
+
+
+def check_env_file(project_root: Path) -> bool:
+ """Check .env file configuration"""
+ print_header("Environment Configuration")
+
+ env_file = project_root / ".env"
+ env_example = project_root / ".env.example"
+
+ if env_file.exists():
+ print_success(".env file exists")
+
+ # Check for required keys (without revealing values)
+ required_keys = [
+ "OPENAI_API_KEY",
+ ]
+ optional_keys = [
+ "ANTHROPIC_API_KEY",
+ "PERPLEXITY_API_KEY",
+ "DASHSCOPE_API_KEY",
+ ]
+
+ try:
+ with open(env_file) as f:
+ content = f.read()
+ lines = content.split("\n")
+ env_vars = {}
+ for line in lines:
+ line = line.strip()
+ if line and not line.startswith("#") and "=" in line:
+ key = line.split("=")[0].strip()
+ value = line.split("=", 1)[1].strip() if "=" in line else ""
+ env_vars[key] = value
+
+ for key in required_keys:
+ if key in env_vars and env_vars[key]:
+ print_success(f" โœ“ {key} is set")
+ else:
+ print_warning(f" โš  {key} is not set (required for most features)")
+
+ for key in optional_keys:
+ if key in env_vars and env_vars[key]:
+ print_success(f" โœ“ {key} is set")
+ else:
+ print_info(f" โ—‹ {key} is not set (optional)")
+
+ except Exception as e:
+ print_warning(f"Could not read .env file: {e}")
+
+ return True
+ else:
+ print_warning(".env file not found")
+ if env_example.exists():
+ print_info("Copy .env.example to .env and configure your API keys")
+ else:
+ print_info("Create a .env file with your API keys (e.g., OPENAI_API_KEY)")
+ return False
+
+
+def main():
+ """Main function"""
+ print("\n" + "=" * 60)
+ print("๐Ÿ” DeepTutor Installation Checker")
+ print("=" * 60)
+ print("Checking all dependencies and configurations...")
+
+ # Get project root
+ script_dir = Path(__file__).parent
+ project_root = script_dir.parent
+
+ print_info(f"Project root: {project_root}")
+
+ # Track overall status
+ all_checks_passed = True
+ summary = []
+
+ # 1. Python environment
+ if check_python_environment():
+ summary.append(("Python Environment", "โœ… OK"))
+ else:
+ summary.append(("Python Environment", "โŒ Issues found"))
+ all_checks_passed = False
+
+ # 2. Backend packages
+ backend_ok, backend_installed, backend_missing = check_backend_packages()
+ if backend_ok:
+ summary.append(("Backend Dependencies", f"โœ… OK ({backend_installed} packages)"))
+ else:
+ summary.append(
+ ("Backend Dependencies", f"โŒ {backend_missing} missing, {backend_installed} installed")
+ )
+ all_checks_passed = False
+
+ # 3. Frontend packages
+ frontend_ok, frontend_installed, frontend_missing = check_frontend_packages(project_root)
+ if frontend_ok:
+ summary.append(("Frontend Dependencies", f"โœ… OK ({frontend_installed} packages)"))
+ else:
+ summary.append(
+ (
+ "Frontend Dependencies",
+ f"โŒ {frontend_missing} missing, {frontend_installed} installed",
+ )
+ )
+ all_checks_passed = False
+
+ # 4. System tools
+ check_system_tools()
+ summary.append(("System Tools", "โœ… Checked"))
+
+ # 5. Environment configuration
+ if check_env_file(project_root):
+ summary.append(("Environment Config", "โœ… .env exists"))
+ else:
+ summary.append(("Environment Config", "โš ๏ธ .env missing"))
+
+ # Print summary
+ print_header("Summary")
+
+ for item, status in summary:
+ print(f" {item}: {status}")
+
+ print("")
+ if all_checks_passed:
+ print_success("All required dependencies are installed!")
+ print_info("You can start DeepTutor with: python scripts/start_web.py")
+ else:
+ print_error("Some dependencies are missing!")
+ print_info("Run: python scripts/install_all.py")
+ print_info("Or manually install missing packages")
+
+ print("=" * 60 + "\n")
+
+ return 0 if all_checks_passed else 1
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except KeyboardInterrupt:
+ print("\n\nโš ๏ธ Check interrupted by user")
+ sys.exit(1)
+ except Exception as e:
+ print_error(f"\nโŒ Unexpected error: {e}")
+ import traceback
+
+ traceback.print_exc()
+ sys.exit(1)
+
diff --git a/scripts/install_all.py b/scripts/install_all.py
index e3ce35996..bcd40ba70 100644
--- a/scripts/install_all.py
+++ b/scripts/install_all.py
@@ -145,10 +145,10 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
print_error(f"Error installing core dependencies: {e}")
return False
- # Stage 2: Install lightrag-hku
- print_info("Stage 2/3: Installing lightrag-hku...")
+ # Stage 2: Install llama-index
+ print_info("Stage 2/3: Installing llama-index...")
try:
- cmd = [sys.executable, "-m", "pip", "install", "lightrag-hku>=1.0.0"]
+ cmd = [sys.executable, "-m", "pip", "install", "llama-index>=0.14.12"]
result = subprocess.run(
cmd,
check=False,
@@ -158,12 +158,14 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
text=True,
)
if result.returncode != 0:
- print_warning("lightrag-hku installation had issues, continuing...")
+ print_warning("llama-index installation had issues, continuing...")
except Exception as e:
- print_warning(f"lightrag-hku installation error: {e}")
+ print_warning(f"llama-index installation error: {e}")
- # Stage 3: Install raganything with special handling
- print_info("Stage 3/3: Installing raganything (this may take a while)...")
+ # Stage 3: Install raganything (includes lightrag-hku as dependency)
+ print_info(
+ "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
+ )
try:
# First try normal install
cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0"]
@@ -192,6 +194,23 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
except Exception as e:
print_warning(f"raganything installation error: {e}")
+ # Stage 4: Install docling (alternative parser for Office/HTML documents)
+ print_info("Stage 4/4: Installing docling (document parser for Office/HTML)...")
+ try:
+ cmd = [sys.executable, "-m", "pip", "install", "docling>=2.31.0"]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=600, # 10 minutes
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ print_warning("docling installation had issues (optional, can be skipped)")
+ except Exception as e:
+ print_warning(f"docling installation error (optional): {e}")
+
# Try to install any remaining optional deps
try:
optional_deps = ["perplexityai>=0.1.0", "dashscope>=1.14.0"]
@@ -521,7 +540,15 @@ def verify_installation(project_root: Path) -> bool:
# Check backend key packages
print_info("Checking backend key packages...")
- backend_packages = ["fastapi", "uvicorn", "openai", "lightrag_hku", "raganything"]
+ backend_packages = [
+ "fastapi",
+ "uvicorn",
+ "openai",
+ "lightrag_hku",
+ "raganything",
+ "llama_index",
+ "docling",
+ ]
for package in backend_packages:
try:
@@ -530,12 +557,18 @@ def verify_installation(project_root: Path) -> bool:
__import__("lightrag")
elif package == "raganything":
__import__("raganything")
+ elif package == "docling":
+ __import__("docling")
else:
__import__(package)
print_success(f" โœ“ {package}")
except ImportError:
- print_error(f" โœ— {package} not installed")
- all_ok = False
+ if package == "docling":
+ # docling is optional
+ print_warning(f" โš  {package} not installed (optional, for Office/HTML parsing)")
+ else:
+ print_error(f" โœ— {package} not installed")
+ all_ok = False
# Check frontend node_modules
print_info("Checking frontend dependencies...")
diff --git a/scripts/install_all.sh b/scripts/install_all.sh
index 7e6fb6012..ae6afe229 100644
--- a/scripts/install_all.sh
+++ b/scripts/install_all.sh
@@ -129,17 +129,21 @@ install_with_pip_staged() {
return 1
fi
- # Stage 2: lightrag-hku
- print_info "Stage 2/3: Installing lightrag-hku..."
- python -m pip install "lightrag-hku>=1.0.0" || print_warning "lightrag-hku installation had issues"
+ # Stage 2: llama-index
+ print_info "Stage 2/3: Installing llama-index..."
+ python -m pip install "llama-index>=0.14.12" || print_warning "llama-index installation had issues"
- # Stage 3: raganything (complex dependencies)
- print_info "Stage 3/3: Installing raganything (this may take a while)..."
+ # Stage 3: raganything (includes lightrag-hku as dependency)
+ print_info "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
if ! python -m pip install "raganything>=0.1.0"; then
print_warning "Standard install failed, trying with --no-deps..."
python -m pip install "raganything>=0.1.0" --no-deps || print_warning "raganything installation had issues"
fi
+ # Stage 4: docling (alternative parser for Office/HTML documents)
+ print_info "Stage 4/4: Installing docling (document parser for Office/HTML)..."
+ python -m pip install "docling>=2.31.0" || print_warning "docling installation had issues (optional, can be skipped)"
+
# Optional deps
python -m pip install "perplexityai>=0.1.0" "dashscope>=1.14.0" 2>/dev/null || true
@@ -343,6 +347,21 @@ else
ALL_OK=false
fi
+# Check llama_index
+if python -c "import llama_index" 2>/dev/null; then
+ print_success " โœ“ llama_index"
+else
+ print_error " โœ— llama_index not installed"
+ ALL_OK=false
+fi
+
+# Check docling (optional)
+if python -c "import docling" 2>/dev/null; then
+ print_success " โœ“ docling"
+else
+ print_warning " โš  docling not installed (optional, for Office/HTML parsing)"
+fi
+
# Check frontend node_modules
print_info "Checking frontend dependencies..."
diff --git a/scripts/start_web.py b/scripts/start_web.py
index 2884c2275..dd5ba6b61 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -224,9 +224,9 @@ def start_backend():
try:
for line in iter(process.stdout.readline, ""):
if line:
- print_flush(f"[Backend] {line.rstrip()}")
+ print_flush(f"[Backend] {line.rstrip()}")
except Exception as e:
- print_flush(f"[Backend] Log output error: {e}")
+ print_flush(f"[Backend] Log output error: {e}")
log_thread = threading.Thread(target=log_output, daemon=True)
log_thread.start()
diff --git a/src/api/main.py b/src/api/main.py
index e13763ed8..66ee5072e 100644
--- a/src/api/main.py
+++ b/src/api/main.py
@@ -23,6 +23,7 @@ from src.api.routers import (
)
from src.logging import get_logger
+# Note: Don't set service_prefix here - start_web.py already adds [Backend] prefix
logger = get_logger("API")
CONFIG_DRIFT_ERROR_TEMPLATE = (
@@ -130,6 +131,17 @@ async def lifespan(app: FastAPI):
# Validate configuration consistency
validate_tool_consistency()
+ # Initialize LLM client early to set environment variables for LightRAG
+ # LightRAG reads OPENAI_API_KEY from os.environ internally, so we must
+ # set it before any RAG operations can happen
+ try:
+ from src.services.llm import get_llm_client
+
+ llm_client = get_llm_client()
+ logger.info(f"LLM client initialized: model={llm_client.config.model}")
+ except Exception as e:
+ logger.warning(f"Failed to initialize LLM client at startup: {e}")
+
yield
# Execute on shutdown
logger.info("Application shutdown")
diff --git a/src/config/constants.py b/src/config/constants.py
index a42ddf7b5..e21b62654 100644
--- a/src/config/constants.py
+++ b/src/config/constants.py
@@ -23,12 +23,14 @@ VALID_SOLVE_TOOLS = [
"finish",
]
-# Logging symbols for different log levels
-LOG_SYMBOLS = {
- "DEBUG": "ยท",
- "INFO": "โ—",
- "SUCCESS": "โœ“",
- "WARNING": "โš ",
- "ERROR": "โœ—",
- "CRITICAL": "โœ—",
-}
+# Standard log level tags (used in unified logging format)
+LOG_LEVEL_TAGS = [
+ "DEBUG",
+ "INFO",
+ "SUCCESS",
+ "WARNING",
+ "ERROR",
+ "CRITICAL",
+ "PROGRESS",
+ "COMPLETE",
+]
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
index bb7ff46da..7e8cdfeb6 100644
--- a/src/knowledge/add_documents.py
+++ b/src/knowledge/add_documents.py
@@ -21,13 +21,15 @@ from typing import TYPE_CHECKING, Any, Dict, List
from dotenv import load_dotenv
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
# Attempt imports for dynamic dependencies
try:
- from lightrag.llm.openai import openai_complete_if_cache
from lightrag.utils import EmbeddingFunc
except ImportError:
- # These will be caught during runtime if needed
- openai_complete_if_cache = None
+ # This will be caught during runtime if needed
EmbeddingFunc = None
# Type hinting support for dynamic imports
@@ -219,99 +221,16 @@ class DocumentAdder:
if self.progress_tracker:
from src.knowledge.progress_tracker import ProgressStage
- self.llm_cfg = get_llm_config()
- model = self.llm_cfg.model
- api_key = self.api_key or self.llm_cfg.api_key
- base_url = self.base_url or self.llm_cfg.base_url
-
- # LLM Function Wrapper
- def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- if history_messages is None:
- history_messages = []
- return openai_complete_if_cache(
- model,
- prompt,
- system_prompt=system_prompt,
- history_messages=history_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ # Use unified LLM client from src/services/llm
+ from src.services.llm import get_llm_client
- # Vision Function Wrapper - Robust history handling
- def vision_model_func(
- prompt,
- system_prompt=None,
- history_messages=None,
- image_data=None,
- messages=None,
- **kwargs,
- ):
- if history_messages is None:
- history_messages = []
- # If pre-formatted messages are provided, sanitize them
- if messages:
- safe_messages = self._filter_valid_messages(messages)
- return openai_complete_if_cache(
- model,
- prompt="",
- messages=safe_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ llm_client = get_llm_client()
+ self.llm_cfg = llm_client.config
- # --- Construct Message History ---
- current_messages = []
-
- # 1. Add System Prompt (if provided)
- if system_prompt:
- current_messages.append({"role": "system", "content": system_prompt})
-
- # 2. Add History (Filtering out conflicting system prompts)
- if history_messages:
- # Filter out system messages from history to avoid duplicates/conflicts with the new system_prompt
- filtered_history = [
- msg
- for msg in history_messages
- if isinstance(msg, dict) and msg.get("role") != "system"
- ]
- current_messages.extend(filtered_history)
-
- # 3. Construct New User Message
- user_content: List[Dict[str, Any]] = [{"type": "text", "text": prompt}]
- if image_data:
- user_content.append(
- {
- "type": "image_url",
- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
- }
- )
-
- # 4. Merge Logic: Avoid back-to-back user messages
- if current_messages and current_messages[-1].get("role") == "user":
- last_msg = current_messages[-1]
- # If last content is string, convert to list format first
- if isinstance(last_msg["content"], str):
- last_msg["content"] = [{"type": "text", "text": last_msg["content"]}]
-
- # Append new content blocks
- if isinstance(last_msg["content"], list):
- last_msg["content"].extend(user_content)
- else:
- # Fallback if structure is unexpected, just append new message
- current_messages.append({"role": "user", "content": user_content})
- else:
- current_messages.append({"role": "user", "content": user_content})
-
- return openai_complete_if_cache(
- model,
- prompt="",
- messages=current_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
# Embedding Setup
reset_embedding_client()
@@ -464,36 +383,50 @@ class DocumentAdder:
]
async def fix_structure(self):
- """Robustly moves nested outputs and cleans up."""
- logger.info("Organizing storage structure...")
+ """
+ Clean up parser output directories after image migration.
- # 1. Identify moves
- moves = []
- for doc_dir in self.content_list_dir.glob("*"):
+ NOTE: Image migration and path updates are now handled by the RAG pipeline
+ (raganything.py / raganything_docling.py) BEFORE RAG insertion. This ensures
+ RAG stores the correct canonical image paths (kb/images/) from the start.
+
+ This method now only cleans up empty temporary parser output directories.
+ """
+ logger.info("Checking for leftover parser output directories...")
+
+ # Support both 'auto' (MinerU) and 'docling' parser output directories
+ parser_subdirs = ["auto", "docling"]
+ cleaned_count = 0
+
+ for doc_dir in list(self.content_list_dir.glob("*")):
if not doc_dir.is_dir():
continue
- # Content List
- json_src = next(doc_dir.glob("auto/*_content_list.json"), None)
- if json_src:
- moves.append((json_src, self.content_list_dir / f"{doc_dir.name}.json"))
-
- # Images
- for img in doc_dir.glob("auto/images/*"):
- moves.append((img, self.images_dir / img.name))
-
- # 2. Execute moves
- for src, dest in moves:
- if src.exists():
- await self._run_in_executor(shutil.copy2, src, dest)
-
- # 3. Safe Cleanup: Only delete directories we actually processed
- for doc_dir in self.content_list_dir.glob("*"):
- if doc_dir.is_dir():
- # Safety check: only delete if it looks like a parser output (has 'auto' subdir)
- # This prevents wiping manual user folders in content_list_dir
- if (doc_dir / "auto").exists():
- await self._run_in_executor(shutil.rmtree, doc_dir, ignore_errors=True)
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Check if directory is empty or only contains empty subdirs
+ has_content = any(
+ f.is_file() or (f.is_dir() and any(f.iterdir()))
+ for f in subdir.iterdir()
+ )
+
+ if not has_content:
+ await self._run_in_executor(shutil.rmtree, subdir)
+ cleaned_count += 1
+ except Exception as e:
+ logger.debug(f"Could not clean up {subdir}: {e}")
+
+ # Remove doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ except Exception:
+ pass
+
+ if cleaned_count > 0:
+ logger.info(f"Cleaned up {cleaned_count} empty parser directories")
def extract_numbered_items_for_new_docs(self, processed_files, batch_size=20):
if not processed_files:
diff --git a/src/knowledge/extract_numbered_items.py b/src/knowledge/extract_numbered_items.py
index aa2111942..0fb6abf15 100644
--- a/src/knowledge/extract_numbered_items.py
+++ b/src/knowledge/extract_numbered_items.py
@@ -19,9 +19,8 @@ from typing import Any
sys.path.append(str(Path(__file__).parent.parent.parent))
from dotenv import load_dotenv
-from lightrag.llm.openai import openai_complete_if_cache
-from src.services.llm import get_llm_config
+from src.services.llm import get_llm_client, get_llm_config
load_dotenv(dotenv_path=".env", override=False)
@@ -62,18 +61,18 @@ async def _call_llm_async(
temperature: float = 0.1,
model: str = None,
) -> str:
- """Asynchronously call LLM"""
- # If model not specified, get from env_config
+ """Asynchronously call LLM using unified LLM service"""
+ # Get unified LLM client (handles all provider differences and env var setup)
+ llm_client = get_llm_client()
+ llm_model_func = llm_client.get_model_func()
+
+ # If model not specified, use configured model
if model is None:
- llm_cfg = get_llm_config()
- model = llm_cfg.model
+ model = llm_client.config.model
- result = openai_complete_if_cache(
- model,
+ result = llm_model_func(
prompt,
system_prompt=system_prompt,
- api_key=api_key,
- base_url=base_url,
max_tokens=max_tokens,
temperature=temperature,
)
diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.py
index 2ed8deef7..cff436ec1 100644
--- a/src/knowledge/initializer.py
+++ b/src/knowledge/initializer.py
@@ -21,6 +21,7 @@ import shutil
from src.logging import get_logger
from src.services.embedding import get_embedding_config
from src.services.llm import get_llm_config
+from src.services.rag.components.routing import FileTypeRouter
from src.services.rag.service import RAGService
logger = get_logger("KnowledgeInit")
@@ -186,10 +187,11 @@ class KnowledgeBaseInitializer:
total=0,
)
- # Get all documents in raw directory
+ # Get all documents in raw directory based on provider's supported extensions
doc_files = []
- for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
- doc_files.extend(list(self.raw_dir.glob(ext)))
+ glob_patterns = FileTypeRouter.get_glob_patterns_for_provider(provider)
+ for pattern in glob_patterns:
+ doc_files.extend(list(self.raw_dir.glob(pattern)))
if not doc_files:
logger.warning("No documents found to process")
@@ -274,80 +276,58 @@ class KnowledgeBaseInitializer:
async def fix_structure(self):
"""
- Fix the nested structure created by process_document_complete.
- Flattens content_list directories and moves images to the correct location.
- """
- logger.info("\nFixing directory structure...")
+ Clean up parser output directories after image migration.
- # Find nested content lists
- content_list_moves = []
- for doc_dir in self.content_list_dir.glob("*"):
- if not doc_dir.is_dir():
- continue
+ NOTE: Image migration and path updates are now handled by the RAG pipeline
+ (raganything.py / raganything_docling.py) BEFORE RAG insertion. This ensures
+ RAG stores the correct canonical image paths (kb/images/) from the start.
- auto_dir = doc_dir / "auto"
- if not auto_dir.exists():
- continue
+ This method now only:
+ 1. Checks if there are any leftover nested directories to clean up
+ 2. Removes empty temporary parser output directories
- # Find the _content_list.json file
- for json_file in auto_dir.glob("*_content_list.json"):
- target_file = self.content_list_dir / f"{doc_dir.name}.json"
- content_list_moves.append((json_file, target_file))
+ Supports both 'auto' (MinerU) and 'docling' parser output directories.
+ """
+ logger.info("\nChecking for leftover parser output directories...")
- # Move content list files
- for source, target in content_list_moves:
- try:
- shutil.copy2(source, target)
- logger.info(f" โœ“ Moved: {source.name} -> {target.name}")
- except Exception as e:
- logger.error(f" โœ— Error moving {source.name}: {e!s}")
+ # Support both 'auto' (MinerU) and 'docling' parser output directories
+ parser_subdirs = ["auto", "docling"]
+ cleaned_count = 0
- # Find and move nested images
- for doc_dir in self.content_list_dir.glob("*"):
+ # Find and remove empty parser output directories
+ for doc_dir in list(self.content_list_dir.glob("*")):
if not doc_dir.is_dir():
continue
- auto_dir = doc_dir / "auto"
- if not auto_dir.exists():
- continue
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Check if directory is empty or only contains empty subdirs
+ has_content = any(
+ f.is_file() or (f.is_dir() and any(f.iterdir()))
+ for f in subdir.iterdir()
+ )
+
+ if not has_content:
+ shutil.rmtree(subdir)
+ cleaned_count += 1
+ logger.debug(f" Removed empty directory: {subdir}")
+ except Exception as e:
+ logger.debug(f" Could not clean up {subdir}: {e}")
+
+ # Remove doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ logger.debug(f" Removed empty directory: {doc_dir}")
+ except Exception:
+ pass
- images_dir = auto_dir / "images"
- if images_dir.exists() and images_dir.is_dir():
- image_count = 0
- # Ensure target directory exists
- self.images_dir.mkdir(parents=True, exist_ok=True)
-
- for img_file in images_dir.glob("*"):
- if img_file.is_file() and img_file.exists():
- target_img = self.images_dir / img_file.name
- if not target_img.exists():
- try:
- # Ensure source file exists
- if not img_file.exists():
- logger.warning(f" โš  Source image not found: {img_file}")
- continue
- shutil.copy2(img_file, target_img)
- image_count += 1
- except FileNotFoundError:
- logger.error(
- f" โœ— Error moving image {img_file.name}: Source file not found: {img_file}"
- )
- except Exception as e:
- logger.error(f" โœ— Error moving image {img_file.name}: {e!s}")
-
- if image_count > 0:
- logger.info(f" โœ“ Moved {image_count} images from {doc_dir.name}/auto/images/")
-
- # Clean up nested directories
- for doc_dir in self.content_list_dir.glob("*"):
- if doc_dir.is_dir():
- try:
- shutil.rmtree(doc_dir)
- logger.info(f" โœ“ Cleaned up: {doc_dir.name}/")
- except Exception as e:
- logger.error(f" โœ— Error removing {doc_dir.name}: {e!s}")
-
- logger.info("โœ“ Structure fixed!")
+ if cleaned_count > 0:
+ logger.info(f"โœ“ Cleaned up {cleaned_count} empty parser directories")
+ else:
+ logger.info("โœ“ No cleanup needed (structure already organized)")
def extract_numbered_items(self, batch_size: int = 20):
"""
@@ -563,6 +543,10 @@ Example usage:
return
# Collect document files
+ # Use provider from env var or default to raganything (most comprehensive)
+ provider = os.getenv("RAG_PROVIDER", "raganything")
+ glob_patterns = FileTypeRouter.get_glob_patterns_for_provider(provider)
+
doc_files = []
if args.docs:
doc_files.extend(args.docs)
@@ -570,8 +554,8 @@ Example usage:
if args.docs_dir:
docs_dir = Path(args.docs_dir)
if docs_dir.exists() and docs_dir.is_dir():
- for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
- doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+ for pattern in glob_patterns:
+ doc_files.extend([str(f) for f in docs_dir.glob(pattern)])
else:
logger.error(f"Error: Documents directory not found: {args.docs_dir}")
return
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index 32c04525c..b58173a56 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -12,6 +12,8 @@ import json
from pathlib import Path
import shutil
+from src.services.rag.components.routing import FileTypeRouter
+
class KnowledgeBaseManager:
"""Manager for knowledge bases"""
@@ -406,8 +408,20 @@ class KnowledgeBaseManager:
if not folder.is_dir():
raise ValueError(f"Path is not a directory: {folder}")
- # Get supported files in folder
- supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}
+ # Get RAG provider from KB metadata to determine supported extensions
+ kb_dir = self.base_dir / kb_name
+ metadata_file = kb_dir / "metadata.json"
+ provider = "raganything" # default to most comprehensive
+ if metadata_file.exists():
+ try:
+ with open(metadata_file, encoding="utf-8") as f:
+ metadata = json.load(f)
+ provider = metadata.get("rag_provider") or "raganything"
+ except Exception:
+ pass
+
+ # Get supported files in folder based on provider
+ supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
files: list[Path] = []
for ext in supported_extensions:
files.extend(folder.glob(f"**/*{ext}"))
@@ -522,12 +536,13 @@ class KnowledgeBaseManager:
return True
- def scan_linked_folder(self, folder_path: str) -> list[str]:
+ def scan_linked_folder(self, folder_path: str, provider: str = "raganything") -> list[str]:
"""
Scan a linked folder and return list of supported file paths.
Args:
folder_path: Path to folder
+ provider: RAG provider to determine supported extensions (default: raganything)
Returns:
List of file paths (as strings)
@@ -537,7 +552,7 @@ class KnowledgeBaseManager:
if not folder.exists() or not folder.is_dir():
return []
- supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}
+ supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
files = []
for ext in supported_extensions:
@@ -582,8 +597,20 @@ class KnowledgeBaseManager:
except Exception:
pass
- # Scan current files
- supported_extensions = {".pdf", ".docx", ".doc", ".txt", ".md", ".markdown"}
+ # Get RAG provider from KB metadata to determine supported extensions
+ kb_dir = self.base_dir / kb_name
+ metadata_file = kb_dir / "metadata.json"
+ provider = "raganything" # default to most comprehensive
+ if metadata_file.exists():
+ try:
+ with open(metadata_file, encoding="utf-8") as f:
+ metadata = json.load(f)
+ provider = metadata.get("rag_provider") or "raganything"
+ except Exception:
+ pass
+
+ # Scan current files based on provider's supported extensions
+ supported_extensions = FileTypeRouter.get_extensions_for_provider(provider)
new_files = []
modified_files = []
diff --git a/src/knowledge/start_kb.py b/src/knowledge/start_kb.py
index 6670f29d7..70e2c1340 100644
--- a/src/knowledge/start_kb.py
+++ b/src/knowledge/start_kb.py
@@ -18,6 +18,8 @@ try:
from .extract_numbered_items import process_content_list
from .initializer import KnowledgeBaseInitializer
from .manager import KnowledgeBaseManager
+
+ from src.services.rag.components.routing import FileTypeRouter
except ImportError:
# If relative import fails, means this file is run directly
# Add parent directory to path
@@ -28,6 +30,7 @@ except ImportError:
from src.knowledge.extract_numbered_items import process_content_list
from src.knowledge.initializer import KnowledgeBaseInitializer
from src.knowledge.manager import KnowledgeBaseManager
+ from src.services.rag.components.routing import FileTypeRouter
def list_knowledge_bases():
@@ -123,6 +126,12 @@ async def init_knowledge_base(args):
return
# Collect document files
+ # Use provider from env var or default to raganything (most comprehensive)
+ import os
+
+ provider = os.getenv("RAG_PROVIDER", "raganything")
+ glob_patterns = FileTypeRouter.get_glob_patterns_for_provider(provider)
+
doc_files = []
if args.docs:
doc_files.extend(args.docs)
@@ -130,8 +139,8 @@ async def init_knowledge_base(args):
if args.docs_dir:
docs_dir = Path(args.docs_dir)
if docs_dir.exists() and docs_dir.is_dir():
- for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
- doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+ for pattern in glob_patterns:
+ doc_files.extend([str(f) for f in docs_dir.glob(pattern)])
else:
print(f"โœ— Error: Document directory does not exist: {args.docs_dir}\n")
return
diff --git a/src/logging/__init__.py b/src/logging/__init__.py
index 1ae905dac..fac531675 100644
--- a/src/logging/__init__.py
+++ b/src/logging/__init__.py
@@ -39,6 +39,7 @@ from .adapters import (
from .config import (
LoggingConfig,
get_default_log_dir,
+ get_global_log_level,
load_logging_config,
)
@@ -58,6 +59,7 @@ from .logger import (
LogLevel,
get_logger,
reset_logger,
+ set_default_service_prefix,
)
# Statistics tracking
@@ -75,6 +77,7 @@ __all__ = [
"LogLevel",
"get_logger",
"reset_logger",
+ "set_default_service_prefix",
"ConsoleFormatter",
"FileFormatter",
# Handlers
@@ -100,4 +103,5 @@ __all__ = [
"LoggingConfig",
"load_logging_config",
"get_default_log_dir",
+ "get_global_log_level",
]
diff --git a/src/logging/adapters/lightrag.py b/src/logging/adapters/lightrag.py
index 52adaff41..6e59c2dd3 100644
--- a/src/logging/adapters/lightrag.py
+++ b/src/logging/adapters/lightrag.py
@@ -4,6 +4,7 @@ LightRAG Log Forwarder
======================
Forwards LightRAG and RAG-Anything logs to DeepTutor's unified logging system.
+Uses the unified global log level from config/main.yaml -> logging.level
"""
from contextlib import contextmanager
@@ -31,17 +32,21 @@ class LightRAGLogForwarder(logging.Handler):
def emit(self, record: logging.LogRecord):
"""
- Forward log record to DeepTutor logger.
- All logs are forwarded as info level to maintain consistent format.
+ Forward log record to DeepTutor logger with proper level mapping.
"""
try:
- # Get the original message directly without adding [LightRAG] prefix
- # LightRAG already formats messages appropriately (e.g., "DEBUG: xxx" for debug logs)
message = record.getMessage()
- # Use info() for all levels to maintain consistent format
- # This ensures all logs appear as [RAGTool] ... (or [RAGTool] DEBUG: ... for debug)
- self.ai_tutor_logger.info(message)
+ # Map LightRAG log levels to DeepTutor logger methods
+ level = record.levelno
+ if level >= logging.ERROR:
+ self.ai_tutor_logger.error(message)
+ elif level >= logging.WARNING:
+ self.ai_tutor_logger.warning(message)
+ elif level >= logging.INFO:
+ self.ai_tutor_logger.info(message)
+ else:
+ self.ai_tutor_logger.debug(message)
except Exception:
# Avoid errors in forwarding from affecting main flow
@@ -50,35 +55,35 @@ class LightRAGLogForwarder(logging.Handler):
def get_lightrag_forwarding_config() -> dict:
"""
- Load LightRAG forwarding configuration from main.yaml.
+ Load LightRAG forwarding configuration from config/main.yaml.
Returns:
dict: Configuration dictionary with defaults if not found
"""
try:
+ from ..config import get_global_log_level
from src.services.config import load_config_with_main
- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
project_root = Path(__file__).resolve().parent.parent.parent.parent
config = load_config_with_main("solve_config.yaml", project_root)
+ logging_config = config.get("logging", {})
- forwarding_config = config.get("logging", {}).get("lightrag_forwarding", {})
+ # Use the unified global log level
+ level = get_global_log_level()
return {
- "enabled": forwarding_config.get("enabled", True),
- "min_level": forwarding_config.get("min_level", "INFO"),
- "add_prefix": forwarding_config.get("add_prefix", True),
- "logger_names": forwarding_config.get(
- "logger_names", {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"}
+ "enabled": True,
+ "min_level": level,
+ "logger_names": logging_config.get(
+ "rag_logger_names", {"knowledge_init": "RAG-Init", "rag_tool": "RAG"}
),
}
except Exception:
# Return defaults if config loading fails
return {
"enabled": True,
- "min_level": "INFO",
- "add_prefix": True,
- "logger_names": {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"},
+ "min_level": "DEBUG",
+ "logger_names": {"knowledge_init": "RAG-Init", "rag_tool": "RAG"},
}
diff --git a/src/logging/config.py b/src/logging/config.py
index e8d16f09e..f41ca2b51 100644
--- a/src/logging/config.py
+++ b/src/logging/config.py
@@ -2,42 +2,36 @@
Logging Configuration
=====================
-Configuration settings for the logging system.
+Unified logging configuration for the entire DeepTutor system.
+A single `level` parameter controls all logging (including RAG modules).
"""
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional
+from typing import Dict, Optional
@dataclass
class LoggingConfig:
"""Configuration for the logging system."""
+ # Global log level (controls entire system including RAG modules)
+ level: str = "DEBUG"
+
# Output settings
console_output: bool = True
file_output: bool = True
- # Log levels
- console_level: str = "INFO"
- file_level: str = "DEBUG"
-
# Log directory (relative to project root or absolute)
log_dir: Optional[str] = None
+ # RAG module logger name mapping
+ rag_logger_names: Optional[Dict[str, str]] = None
+
# File rotation settings
max_bytes: int = 10 * 1024 * 1024 # 10MB
backup_count: int = 5
- # WebSocket streaming
- websocket_enabled: bool = True
- websocket_queue_size: int = 1000
-
- # LightRAG forwarding
- lightrag_forwarding_enabled: bool = True
- lightrag_min_level: str = "INFO"
- lightrag_add_prefix: bool = True
-
def get_default_log_dir() -> Path:
"""Get the default log directory."""
@@ -45,6 +39,22 @@ def get_default_log_dir() -> Path:
return project_root / "data" / "user" / "logs"
+def get_global_log_level() -> str:
+ """
+ Get the global log level from config/main.yaml -> logging.level
+ Default: DEBUG
+ """
+ try:
+ from src.services.config import load_config_with_main
+
+ project_root = Path(__file__).resolve().parent.parent.parent
+ config = load_config_with_main("solve_config.yaml", project_root)
+ logging_config = config.get("logging", {})
+ return logging_config.get("level", "DEBUG").upper()
+ except Exception:
+ return "DEBUG"
+
+
def load_logging_config() -> LoggingConfig:
"""
Load logging configuration from config files.
@@ -59,22 +69,14 @@ def load_logging_config() -> LoggingConfig:
config = load_config_with_main("solve_config.yaml", project_root)
logging_config = config.get("logging", {})
+ level = get_global_log_level()
return LoggingConfig(
+ level=level,
console_output=logging_config.get("console_output", True),
- file_output=logging_config.get("file_output", True),
- console_level=logging_config.get("console_level", "INFO"),
- file_level=logging_config.get("file_level", "DEBUG"),
+ file_output=logging_config.get("save_to_file", True),
log_dir=get_path_from_config(config, "user_log_dir"),
- lightrag_forwarding_enabled=logging_config.get("lightrag_forwarding", {}).get(
- "enabled", True
- ),
- lightrag_min_level=logging_config.get("lightrag_forwarding", {}).get(
- "min_level", "INFO"
- ),
- lightrag_add_prefix=logging_config.get("lightrag_forwarding", {}).get(
- "add_prefix", True
- ),
+ rag_logger_names=logging_config.get("rag_logger_names"),
)
except Exception:
return LoggingConfig()
diff --git a/src/logging/handlers/console.py b/src/logging/handlers/console.py
index ea4f3d99a..521cb867d 100644
--- a/src/logging/handlers/console.py
+++ b/src/logging/handlers/console.py
@@ -3,59 +3,15 @@
Console Log Handler
===================
-Color-coded console output with symbols.
+Color-coded console output with standard level tags.
"""
import logging
import sys
+from typing import Optional
-
-class ConsoleFormatter(logging.Formatter):
- """
- Clean console formatter with colors and symbols.
- Format: [Module] Symbol Message
- """
-
- # ANSI color codes
- COLORS = {
- "DEBUG": "\033[90m", # Gray
- "INFO": "\033[37m", # White
- "SUCCESS": "\033[32m", # Green
- "WARNING": "\033[33m", # Yellow
- "ERROR": "\033[31m", # Red
- "CRITICAL": "\033[35m", # Magenta
- }
- RESET = "\033[0m"
- BOLD = "\033[1m"
- DIM = "\033[2m"
-
- # Symbols for different log types
- SYMBOLS = {
- "DEBUG": "ยท",
- "INFO": "โ—",
- "SUCCESS": "โœ“",
- "WARNING": "โš ",
- "ERROR": "โœ—",
- "CRITICAL": "โœ—",
- }
-
- def format(self, record: logging.LogRecord) -> str:
- # Get module name (padded to 12 chars for alignment)
- module = getattr(record, "module_name", record.name)
- module_padded = f"[{module}]".ljust(14)
-
- # Get symbol (can be overridden via record.symbol)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "โ—"))
-
- # Get color
- level = getattr(record, "display_level", record.levelname)
- color = self.COLORS.get(level, self.COLORS["INFO"])
-
- # Format message
- message = record.getMessage()
-
- # Build output: [Module] โ— Message
- return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"
+# Import ConsoleFormatter from the main logger module to avoid duplication
+from ..logger import ConsoleFormatter
class ConsoleHandler(logging.StreamHandler):
@@ -63,13 +19,14 @@ class ConsoleHandler(logging.StreamHandler):
Console handler with color-coded output.
"""
- def __init__(self, level: int = logging.INFO):
+ def __init__(self, level: int = logging.INFO, service_prefix: Optional[str] = None):
"""
Initialize console handler.
Args:
level: Minimum log level to display
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
"""
super().__init__(sys.stdout)
self.setLevel(level)
- self.setFormatter(ConsoleFormatter())
+ self.setFormatter(ConsoleFormatter(service_prefix=service_prefix))
diff --git a/src/logging/handlers/file.py b/src/logging/handlers/file.py
index 7ae3dce3a..c7985d3bc 100644
--- a/src/logging/handlers/file.py
+++ b/src/logging/handlers/file.py
@@ -13,24 +13,8 @@ from logging.handlers import RotatingFileHandler as BaseRotatingFileHandler
from pathlib import Path
from typing import Optional
-
-class FileFormatter(logging.Formatter):
- """
- Detailed file formatter for log files.
- Format: TIMESTAMP [LEVEL] [Module] Message
- """
-
- def __init__(self):
- super().__init__(
- fmt="%(asctime)s [%(levelname)-8s] [%(module_name)-12s] %(message)s",
- datefmt="%Y-%m-%d %H:%M:%S",
- )
-
- def format(self, record: logging.LogRecord) -> str:
- # Ensure module_name exists
- if not hasattr(record, "module_name"):
- record.module_name = record.name
- return super().format(record)
+# Import FileFormatter from the main logger module to avoid duplication
+from ..logger import FileFormatter
class FileHandler(logging.FileHandler):
@@ -143,7 +127,7 @@ class JSONFileHandler(logging.Handler):
}
# Add extra fields if present
- for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
+ for key in ["display_level", "tool_name", "elapsed_ms", "tokens"]:
if hasattr(record, key):
entry[key] = getattr(record, key)
@@ -180,7 +164,7 @@ def create_task_logger(
log_path.mkdir(parents=True, exist_ok=True)
# Create logger
- logger = logging.getLogger(f"ai_tutor.{module_name}.{task_id}")
+ logger = logging.getLogger(f"deeptutor.{module_name}.{task_id}")
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
logger.propagate = False
diff --git a/src/logging/handlers/websocket.py b/src/logging/handlers/websocket.py
index 92c0c3b35..754339ad3 100644
--- a/src/logging/handlers/websocket.py
+++ b/src/logging/handlers/websocket.py
@@ -8,6 +8,7 @@ Handlers for streaming logs to WebSocket clients.
import asyncio
import logging
+from typing import Optional
class WebSocketLogHandler(logging.Handler):
@@ -25,27 +26,24 @@ class WebSocketLogHandler(logging.Handler):
await websocket.send_json(log_entry)
"""
- # Symbols for different log types (matching ConsoleFormatter)
- SYMBOLS = {
- "DEBUG": "ยท",
- "INFO": "โ—",
- "SUCCESS": "โœ“",
- "WARNING": "โš ",
- "ERROR": "โœ—",
- "CRITICAL": "โœ—",
- }
-
- def __init__(self, queue: asyncio.Queue, include_module: bool = True):
+ def __init__(
+ self,
+ queue: asyncio.Queue,
+ include_module: bool = True,
+ service_prefix: Optional[str] = None,
+ ):
"""
Initialize WebSocket log handler.
Args:
queue: asyncio.Queue to put log entries into
include_module: Whether to include module name in output
+ service_prefix: Optional service layer prefix (e.g., "Backend")
"""
super().__init__()
self.queue = queue
self.include_module = include_module
+ self.service_prefix = service_prefix
self.setFormatter(logging.Formatter("%(message)s"))
def emit(self, record: logging.LogRecord):
@@ -53,25 +51,31 @@ class WebSocketLogHandler(logging.Handler):
try:
msg = self.format(record)
- # Get symbol
+ # Get display level
display_level = getattr(record, "display_level", record.levelname)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(display_level, "โ—"))
# Get module name
module_name = getattr(record, "module_name", record.name)
- # Build formatted content
- if self.include_module:
- content = f"[{module_name}] {symbol} {msg}"
+ # Build formatted content with standard level tags (compact format)
+ level_tag = display_level
+ if self.service_prefix:
+ service_tag = f"[{self.service_prefix}]"
+ if self.include_module:
+ content = f"{service_tag} {level_tag} [{module_name}] {msg}"
+ else:
+ content = f"{service_tag} {level_tag} {msg}"
else:
- content = f"{symbol} {msg}"
+ if self.include_module:
+ content = f"{level_tag} [{module_name}] {msg}"
+ else:
+ content = f"{level_tag} {msg}"
# Construct structured message
log_entry = {
"type": "log",
"level": display_level,
"module": module_name,
- "symbol": symbol,
"content": content,
"message": msg,
"timestamp": record.created,
@@ -93,7 +97,7 @@ class LogInterceptor:
Usage:
queue = asyncio.Queue()
- logger = logging.getLogger("ai_tutor.Solver")
+ logger = logging.getLogger("deeptutor.Solver")
with LogInterceptor(logger, queue):
# All logs from this logger will be streamed to queue
diff --git a/src/logging/logger.py b/src/logging/logger.py
index 78640595c..f1b0787f7 100644
--- a/src/logging/logger.py
+++ b/src/logging/logger.py
@@ -4,13 +4,14 @@ Core Logger Implementation
==========================
Unified logging with consistent format across all modules.
-Format: [Module] Symbol Message
+Format: [LEVEL] [Module] Message
Example outputs:
- [Solver] โœ“ Ready in 2.3s
- [Research] โ†’ Starting deep research...
- [Guide] โ†’ Compiling knowledge points
- [Knowledge] โœ“ Indexed 150 documents
+ [INFO] [Solver] Ready in 2.3s
+ [INFO] [Research] Starting deep research...
+ [INFO] [Guide] Compiling knowledge points
+ [INFO] [Knowledge] Indexed 150 documents
+ [ERROR] [EmbeddingClient] Embedding request failed
"""
from datetime import datetime
@@ -21,26 +22,26 @@ from pathlib import Path
import sys
from typing import Any, List, Optional, Union
-from src.config.constants import LOG_SYMBOLS, PROJECT_ROOT
+from src.config.constants import PROJECT_ROOT
class LogLevel(Enum):
- """Log levels with associated symbols"""
+ """Log levels with standard tags"""
- DEBUG = ("DEBUG", "ยท") # Dot for debug
- INFO = ("INFO", "โ—") # Circle for info
- SUCCESS = ("SUCCESS", "โœ“") # Checkmark for success
- WARNING = ("WARNING", "โš ") # Warning sign
- ERROR = ("ERROR", "โœ—") # X for error
- CRITICAL = ("CRITICAL", "โœ—") # X for critical
- PROGRESS = ("INFO", "โ†’") # Arrow for progress
- COMPLETE = ("INFO", "โœ“") # Checkmark for completion
+ DEBUG = "DEBUG"
+ INFO = "INFO"
+ SUCCESS = "SUCCESS"
+ WARNING = "WARNING"
+ ERROR = "ERROR"
+ CRITICAL = "CRITICAL"
+ PROGRESS = "PROGRESS"
+ COMPLETE = "COMPLETE"
class ConsoleFormatter(logging.Formatter):
"""
- Clean console formatter with colors and symbols.
- Format: [Module] Symbol Message
+ Clean console formatter with colors and standard level tags.
+ Format: [LEVEL] [Module] Message
"""
# ANSI color codes
@@ -51,36 +52,46 @@ class ConsoleFormatter(logging.Formatter):
"WARNING": "\033[33m", # Yellow
"ERROR": "\033[31m", # Red
"CRITICAL": "\033[35m", # Magenta
+ "PROGRESS": "\033[36m", # Cyan
+ "COMPLETE": "\033[32m", # Green
}
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
- # Symbols for different log types
- SYMBOLS = LOG_SYMBOLS
+ def __init__(self, service_prefix: Optional[str] = None):
+ """
+ Initialize console formatter.
- def __init__(self):
+ Args:
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
+ """
super().__init__()
+ self.service_prefix = service_prefix
# Check TTY status once during initialization
stdout_tty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
stderr_tty = hasattr(sys.stderr, "isatty") and sys.stderr.isatty()
self.use_colors = stdout_tty or stderr_tty
def format(self, record: logging.LogRecord) -> str:
- # Get module name (padded to 12 chars for alignment)
+ # Get display level (may be custom like SUCCESS, PROGRESS)
+ display_level = getattr(record, "display_level", record.levelname)
+
+ # Get module name
module = getattr(record, "module_name", record.name)
- module_padded = f"[{module}]".ljust(14)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "โ—"))
+
+ # Build module tag [Module]
+ module_tag = f"[{module}]"
+
+ # Build level tag with colon
+ level_tag = f"{display_level}:"
+
# Use pre-computed TTY status
- use_colors = self.use_colors
- if use_colors:
- # Get color
- level = getattr(record, "display_level", record.levelname)
- color = self.COLORS.get(level, self.COLORS["INFO"])
+ if self.use_colors:
+ color = self.COLORS.get(display_level, self.COLORS["INFO"])
dim = self.DIM
reset = self.RESET
else:
- # No colors for non-interactive output
color = ""
dim = ""
reset = ""
@@ -88,8 +99,12 @@ class ConsoleFormatter(logging.Formatter):
# Format message
message = record.getMessage()
- # Build output: [Module] โ— Message
- return f"{dim}{module_padded}{reset} {color}{symbol}{reset} {message}"
+ # Build output: [Backend] [Module] INFO: Message (module first, then level)
+ if self.service_prefix:
+ service_tag = f"[{self.service_prefix}]"
+ return f"{dim}{service_tag}{reset} {dim}{module_tag}{reset} {color}{level_tag}{reset} {message}"
+ else:
+ return f"{dim}{module_tag}{reset} {color}{level_tag}{reset} {message}"
class FileFormatter(logging.Formatter):
@@ -121,6 +136,7 @@ class Logger:
- File logging to user/logs/
- WebSocket streaming support
- Success/progress/complete convenience methods
+ - Optional service layer prefix (Backend/Frontend)
Usage:
logger = Logger("Solver")
@@ -136,6 +152,7 @@ class Logger:
console_output: bool = True,
file_output: bool = True,
log_dir: Optional[Union[str, Path]] = None,
+ service_prefix: Optional[str] = None,
):
"""
Initialize logger.
@@ -146,14 +163,17 @@ class Logger:
console_output: Whether to output to console
file_output: Whether to output to file
log_dir: Log directory (default: ../user/logs/)
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
"""
self.name = name
self.level = getattr(logging, level.upper(), logging.INFO)
+ self.service_prefix = service_prefix
# Create underlying Python logger
- self.logger = logging.getLogger(f"ai_tutor.{name}")
+ self.logger = logging.getLogger(f"deeptutor.{name}")
self.logger.setLevel(logging.DEBUG) # Capture all, filter at handlers
self.logger.handlers.clear()
+ self.logger.propagate = False # Prevent duplicate logs from root logger
# Setup log directory
log_dir_path: Path
if log_dir is None:
@@ -171,13 +191,13 @@ class Logger:
if console_output:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(self.level)
- console_handler.setFormatter(ConsoleFormatter())
+ console_handler.setFormatter(ConsoleFormatter(service_prefix=service_prefix))
self.logger.addHandler(console_handler)
# File handler
if file_output:
timestamp = datetime.now().strftime("%Y%m%d")
- log_file = log_dir_path / f"ai_tutor_{timestamp}.log"
+ log_file = log_dir_path / f"deeptutor_{timestamp}.log"
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG) # Log everything to file
@@ -234,14 +254,12 @@ class Logger:
self,
level: int,
message: str,
- symbol: Optional[str] = None,
display_level: Optional[str] = None,
**kwargs,
):
"""Internal logging method with extra attributes."""
extra = {
"module_name": self.name,
- "symbol": symbol,
"display_level": display_level or logging.getLevelName(level),
}
# Extract standard logging parameters from kwargs
@@ -255,45 +273,43 @@ class Logger:
# Standard logging methods
def debug(self, message: str, **kwargs):
- """Debug level log (ยท)"""
- self._log(logging.DEBUG, message, symbol="ยท", **kwargs)
+ """Debug level log [DEBUG]"""
+ self._log(logging.DEBUG, message, **kwargs)
def info(self, message: str, **kwargs):
- """Info level log (โ—)"""
- self._log(logging.INFO, message, symbol="โ—", **kwargs)
+ """Info level log [INFO]"""
+ self._log(logging.INFO, message, **kwargs)
def warning(self, message: str, **kwargs):
- """Warning level log (โš )"""
- self._log(logging.WARNING, message, symbol="โš ", **kwargs)
+ """Warning level log [WARNING]"""
+ self._log(logging.WARNING, message, **kwargs)
def error(self, message: str, **kwargs):
- """Error level log (โœ—)"""
- self._log(logging.ERROR, message, symbol="โœ—", **kwargs)
+ """Error level log [ERROR]"""
+ self._log(logging.ERROR, message, **kwargs)
def critical(self, message: str, **kwargs):
- """Critical level log (โœ—)"""
- self._log(logging.CRITICAL, message, symbol="โœ—", **kwargs)
+ """Critical level log [CRITICAL]"""
+ self._log(logging.CRITICAL, message, **kwargs)
def exception(self, message: str, **kwargs):
"""Log exception with traceback"""
- self.logger.exception(
- message, extra={"module_name": self.name, "symbol": "โœ—", "display_level": "ERROR"}
- )
+ self.logger.exception(message, extra={"module_name": self.name, "display_level": "ERROR"})
# Convenience methods
def success(self, message: str, elapsed: Optional[float] = None, **kwargs):
- """Success log with checkmark (โœ“)"""
+ """Success log [SUCCESS]"""
if elapsed is not None:
message = f"{message} in {elapsed:.1f}s"
- self._log(logging.INFO, message, symbol="โœ“", display_level="SUCCESS", **kwargs)
+ self._log(logging.INFO, message, display_level="SUCCESS", **kwargs)
def progress(self, message: str, **kwargs):
- """Progress log with arrow (โ†’)"""
- self._log(logging.INFO, message, symbol="โ†’", **kwargs)
+ """Progress log [PROGRESS]"""
+ self._log(logging.INFO, message, display_level="PROGRESS", **kwargs)
def complete(self, message: str, **kwargs):
- """Completion log with checkmark (โœ“)"""
- self._log(logging.INFO, message, symbol="โœ“", display_level="SUCCESS", **kwargs)
+ """Completion log [COMPLETE]"""
+ self._log(logging.INFO, message, display_level="COMPLETE", **kwargs)
def stage(self, stage_name: str, status: str = "start", detail: Optional[str] = None):
"""
@@ -304,15 +320,16 @@ class Logger:
status: One of "start", "running", "complete", "skip", "error"
detail: Optional detail message
"""
- symbols = {
- "start": "โ–ถ",
- "running": "โ—",
- "complete": "โœ“",
- "skip": "โ—‹",
- "error": "โœ—",
- "warning": "โš ",
+ # Map status to display level
+ status_to_level = {
+ "start": "PROGRESS",
+ "running": "INFO",
+ "complete": "SUCCESS",
+ "skip": "INFO",
+ "error": "ERROR",
+ "warning": "WARNING",
}
- symbol = symbols.get(status, "โ—")
+ display_level = status_to_level.get(status, "INFO")
message = f"{stage_name}"
if status == "complete":
@@ -330,10 +347,7 @@ class Logger:
message += f" | {detail}"
level = logging.ERROR if status == "error" else logging.INFO
- display_level = (
- "ERROR" if status == "error" else ("SUCCESS" if status == "complete" else "INFO")
- )
- self._log(level, message, symbol=symbol, display_level=display_level)
+ self._log(level, message, display_level=display_level)
def tool_call(
self, tool_name: str, status: str = "success", elapsed_ms: Optional[float] = None, **kwargs
@@ -346,7 +360,6 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "โœ“" if status == "success" else ("โœ—" if status == "error" else "โ—")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -360,7 +373,6 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
- symbol=symbol,
display_level=display_level,
)
@@ -394,7 +406,7 @@ class Logger:
parts.append(f"{elapsed:.2f}s")
message = " | ".join(parts)
- self._log(logging.DEBUG, message, symbol="โ—†")
+ self._log(logging.DEBUG, message)
def separator(self, char: str = "โ”€", length: int = 50):
"""Print a separator line"""
@@ -420,7 +432,6 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "โœ“" if status == "success" else ("โœ—" if status == "error" else "โ—")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -435,7 +446,6 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
- symbol=symbol,
display_level=display_level,
)
@@ -509,22 +519,20 @@ class Logger:
level: Log level ("DEBUG" for full details, "INFO" for summary)
"""
# Build header
- header_parts = ["[LLM-CALL]"]
+ header_parts = ["LLM-CALL"]
if agent_name:
- header_parts.append(f"[Agent: {agent_name}]")
- header_parts.append(f"[Stage: {stage}]")
- header_parts.append(f"[Model: {model}]")
- header = " ".join(header_parts)
+ header_parts.append(f"Agent: {agent_name}")
+ header_parts.append(f"Stage: {stage}")
+ header_parts.append(f"Model: {model}")
+ header = " | ".join(header_parts)
# Log at appropriate level
log_level = logging.DEBUG if level == "DEBUG" else logging.INFO
if level == "DEBUG":
# Full detailed output
- self._log(log_level, header, symbol="โ—†")
- self._log(
- log_level, "โ”Œโ”€ Input โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€", symbol=" "
- )
+ self._log(log_level, header)
+ self._log(log_level, "--- Input ---")
self._log(
log_level,
(
@@ -532,7 +540,6 @@ class Logger:
if len(system_prompt) > 200
else f"System: {system_prompt}"
),
- symbol=" ",
)
self._log(
log_level,
@@ -541,20 +548,9 @@ class Logger:
if len(user_prompt) > 500
else f"User: {user_prompt}"
),
- symbol=" ",
- )
- self._log(
- log_level, "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€", symbol=" "
- )
- self._log(
- log_level, "โ”Œโ”€ Output โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€", symbol=" "
- )
- self._log(
- log_level, f"{response[:1000]}..." if len(response) > 1000 else response, symbol=" "
- )
- self._log(
- log_level, "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€", symbol=" "
)
+ self._log(log_level, "--- Output ---")
+ self._log(log_level, f"{response[:1000]}..." if len(response) > 1000 else response)
# Token and cost info
token_info_parts = []
@@ -568,17 +564,17 @@ class Logger:
token_info_parts.append(f"cost=${cost:.6f}")
if token_info_parts:
- self._log(log_level, f"[Tokens: {' '.join(token_info_parts)}]", symbol=" ")
+ self._log(log_level, f"Tokens: {' '.join(token_info_parts)}")
else:
# Summary output
token_info = ""
if input_tokens is not None and output_tokens is not None:
- token_info = f" [Tokens: in={input_tokens}, out={output_tokens}, total={input_tokens + output_tokens}]"
+ token_info = f" | Tokens: in={input_tokens}, out={output_tokens}, total={input_tokens + output_tokens}"
if cost is not None:
- token_info += f" [Cost: ${cost:.6f}]"
+ token_info += f" | Cost: ${cost:.6f}"
message = f"{header}{token_info}"
- self._log(log_level, message, symbol="โ—†")
+ self._log(log_level, message)
def update_token_stats(self, summary: dict[str, Any]):
"""Update token statistics (for display manager compatibility)"""
@@ -609,67 +605,99 @@ class Logger:
self.logger.removeHandler(handler)
-# Global logger registry - key is tuple of (name, level, console_output, file_output, log_dir)
-_loggers: dict[tuple[str, str, bool, bool, Optional[str]], "Logger"] = {}
+# Global logger registry - key is tuple of (name, level, console_output, file_output, log_dir, service_prefix)
+_loggers: dict[tuple[str, str, bool, bool, Optional[str], Optional[str]], "Logger"] = {}
+
+# Global default service prefix (can be set at application startup)
+_default_service_prefix: Optional[str] = None
+
+
+def set_default_service_prefix(prefix: Optional[str]):
+ """
+ Set the default service prefix for all new loggers.
+
+ Call this at application startup to set a global prefix like "Backend" or "Frontend".
+
+ Args:
+ prefix: Service prefix (e.g., "Backend", "Frontend") or None to disable
+ """
+ global _default_service_prefix
+ _default_service_prefix = prefix
def get_logger(
name: str = "Main",
- level: str = "INFO",
+ level: Optional[str] = None,
console_output: bool = True,
file_output: bool = True,
log_dir: Optional[str] = None,
+ service_prefix: Optional[str] = None,
) -> Logger:
"""
Get or create a logger instance.
Args:
name: Module name
- level: Log level
+ level: Log level (if None, uses global level from config/main.yaml)
console_output: Enable console output
file_output: Enable file output
log_dir: Log directory (if None, will try to load from config/main.yaml)
+ service_prefix: Optional service prefix (if None, uses default set by set_default_service_prefix)
Returns:
Logger instance
"""
- global _loggers
+ global _loggers, _default_service_prefix
- # If log_dir not provided, try to load from config
- if log_dir is None:
+ # Use default service prefix if not explicitly provided
+ effective_service_prefix = (
+ service_prefix if service_prefix is not None else _default_service_prefix
+ )
+
+ # Load config for log_dir and level
+ effective_level = level
+ if log_dir is None or effective_level is None:
try:
from src.services.config import get_path_from_config, load_config_with_main
- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
- config = load_config_with_main(
- "solve_config.yaml", PROJECT_ROOT
- ) # Use any config to get main.yaml
- log_dir = get_path_from_config(config, "user_log_dir") or config.get("paths", {}).get(
- "user_log_dir"
- )
- if log_dir:
- # Convert relative path to absolute based on project root
- log_dir_path = Path(log_dir)
- if not log_dir_path.is_absolute():
- # Remove leading ./ if present
- log_dir_str = str(log_dir_path).lstrip("./")
- log_dir = str(PROJECT_ROOT / log_dir_str)
- else:
- log_dir = str(log_dir_path)
+ config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)
+
+ # Get log_dir from config
+ if log_dir is None:
+ log_dir = get_path_from_config(config, "user_log_dir") or config.get(
+ "paths", {}
+ ).get("user_log_dir")
+ if log_dir:
+ log_dir_path = Path(log_dir)
+ if not log_dir_path.is_absolute():
+ log_dir_str = str(log_dir_path).lstrip("./")
+ log_dir = str(PROJECT_ROOT / log_dir_str)
+ else:
+ log_dir = str(log_dir_path)
+
+ # Get level from config (unified global level)
+ if effective_level is None:
+ from .config import get_global_log_level
+
+ effective_level = get_global_log_level()
except Exception:
- # Fallback to default
pass
+
+ # Use DEBUG as ultimate fallback
+ if effective_level is None:
+ effective_level = "DEBUG"
+
log_dir_key = str(log_dir) if log_dir is not None else None
- # Create a cache key that includes configuration, using a normalized log_dir
- cache_key = (name, level, console_output, file_output, log_dir_key)
+ cache_key = (name, effective_level, console_output, file_output, log_dir_key, effective_service_prefix)
if cache_key not in _loggers:
_loggers[cache_key] = Logger(
name=name,
- level=level,
+ level=effective_level,
console_output=console_output,
file_output=file_output,
log_dir=log_dir,
+ service_prefix=effective_service_prefix,
)
return _loggers[cache_key]
diff --git a/src/logging/stats/llm_stats.py b/src/logging/stats/llm_stats.py
index 8070240e1..a5552b8b6 100644
--- a/src/logging/stats/llm_stats.py
+++ b/src/logging/stats/llm_stats.py
@@ -4,12 +4,12 @@ LLM Stats Tracker
=================
Simple utility for tracking LLM token usage and costs across all modules.
-Outputs summary to terminal at the end of processing.
+Outputs summary via the unified logging system.
Usage:
from src.logging import LLMStats
- stats = LLMStats()
+ stats = LLMStats("Solver")
# After each LLM call:
stats.add_call(
@@ -19,12 +19,15 @@ Usage:
)
# At the end:
- stats.print_summary()
+ stats.log_summary() # Uses logging system
"""
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:
+ from ..logger import Logger
# Model pricing per 1K tokens (USD)
MODEL_PRICING = {
@@ -150,25 +153,42 @@ class LLMStats:
"cost_usd": self.total_cost,
}
- def print_summary(self):
- """Print summary to terminal."""
+ def log_summary(self, logger: Optional["Logger"] = None):
+ """
+ Log summary using the unified logging system.
+
+ Args:
+ logger: Optional Logger instance. If None, creates one using module_name.
+ """
if len(self.calls) == 0:
return
+ # Import here to avoid circular imports
+ from ..logger import get_logger
+
+ if logger is None:
+ logger = get_logger(self.module_name)
+
total_tokens = self.total_prompt_tokens + self.total_completion_tokens
- print()
- print("=" * 60)
- print(f"๐Ÿ“Š [{self.module_name}] LLM Usage Summary")
- print("=" * 60)
- print(f" Model : {self.model_used or 'Unknown'}")
- print(f" API Calls : {len(self.calls)}")
- print(
- f" Tokens : {total_tokens:,} (Input: {self.total_prompt_tokens:,}, Output: {self.total_completion_tokens:,})"
+ logger.info("=" * 60)
+ logger.info(f"LLM Usage Summary for {self.module_name}")
+ logger.info("=" * 60)
+ logger.info(f"Model : {self.model_used or 'Unknown'}")
+ logger.info(f"API Calls : {len(self.calls)}")
+ logger.info(
+ f"Tokens : {total_tokens:,} (Input: {self.total_prompt_tokens:,}, Output: {self.total_completion_tokens:,})"
)
- print(f" Cost : ${self.total_cost:.6f} USD")
- print("=" * 60)
- print()
+ logger.info(f"Cost : ${self.total_cost:.6f} USD")
+ logger.info("=" * 60)
+
+ def print_summary(self):
+ """
+ Print summary to terminal.
+
+ Deprecated: Use log_summary() instead for consistent logging.
+ """
+ self.log_summary()
def reset(self):
"""Reset all statistics."""
diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.py
index f33f23972..44e2f23cb 100644
--- a/src/services/config/unified_config.py
+++ b/src/services/config/unified_config.py
@@ -537,7 +537,52 @@ class UnifiedConfigManager:
return False
data["active_id"] = config_id
- return self._save_configs(config_type, data)
+ success = self._save_configs(config_type, data)
+
+ # Update environment variables for LightRAG compatibility when LLM config changes
+ if success and config_type == ConfigType.LLM:
+ self._update_openai_env_vars_for_lightrag()
+
+ return success
+
+ def _update_openai_env_vars_for_lightrag(self):
+ """
+ Update OPENAI_API_KEY and OPENAI_BASE_URL environment variables for LightRAG.
+
+ LightRAG's internal functions read directly from os.environ["OPENAI_API_KEY"]
+ instead of using passed parameters. This method ensures the environment
+ variables are updated when the active LLM configuration changes.
+ """
+ try:
+ config = self.get_active_config(ConfigType.LLM)
+ if not config:
+ return
+
+ provider = config.get("provider", "openai")
+ api_key = config.get("api_key", "")
+ base_url = config.get("base_url", "")
+
+ # Only set env vars for OpenAI-compatible providers
+ if provider in ("openai", "azure_openai", "gemini", "deepseek"):
+ if api_key:
+ os.environ["OPENAI_API_KEY"] = api_key
+ logger.debug("Updated OPENAI_API_KEY env var for LightRAG compatibility")
+
+ if base_url:
+ os.environ["OPENAI_BASE_URL"] = base_url
+ logger.debug(f"Updated OPENAI_BASE_URL env var to {base_url}")
+
+ # Reset LLM client singleton to pick up new configuration
+ try:
+ from src.services.llm import reset_llm_client
+
+ reset_llm_client()
+ logger.debug("Reset LLM client singleton after config change")
+ except ImportError:
+ pass
+
+ except Exception as e:
+ logger.warning(f"Failed to update OpenAI env vars: {e}")
def get_env_status(self, config_type: ConfigType) -> Dict[str, bool]:
"""Check which environment variables are configured for a service type."""
diff --git a/src/services/llm/client.py b/src/services/llm/client.py
index f2105600f..941dd1541 100644
--- a/src/services/llm/client.py
+++ b/src/services/llm/client.py
@@ -31,9 +31,38 @@ class LLMClient:
Args:
config: LLM configuration. If None, loads from environment.
"""
+
self.config = config or get_llm_config()
self.logger = get_logger("LLMClient")
+ # Set environment variables for LightRAG compatibility
+ # LightRAG's internal functions (openai_complete_if_cache, etc.) read from
+ # os.environ["OPENAI_API_KEY"] even when api_key is passed as parameter.
+ # We must set these env vars early to ensure all LightRAG operations work.
+ self._setup_openai_env_vars()
+
+ def _setup_openai_env_vars(self):
+ """
+ Set OpenAI environment variables for LightRAG compatibility.
+
+ LightRAG's internal functions read from os.environ["OPENAI_API_KEY"]
+ even when api_key is passed as parameter. This method ensures the
+ environment variables are set for all LightRAG operations.
+ """
+ import os
+
+ binding = getattr(self.config, "binding", "openai")
+
+ # Only set env vars for OpenAI-compatible bindings
+ if binding in ("openai", "azure_openai", "gemini"):
+ if self.config.api_key:
+ os.environ["OPENAI_API_KEY"] = self.config.api_key
+ self.logger.debug("Set OPENAI_API_KEY env var for LightRAG compatibility")
+
+ if self.config.base_url:
+ os.environ["OPENAI_BASE_URL"] = self.config.base_url
+ self.logger.debug(f"Set OPENAI_BASE_URL env var to {self.config.base_url}")
+
async def complete(
self,
prompt: str,
@@ -128,6 +157,7 @@ class LLMClient:
return llm_model_func_via_factory
# OpenAI-compatible bindings use lightrag (has caching)
+ # Note: Environment variables are already set in __init__ via _setup_openai_env_vars()
from lightrag.llm.openai import openai_complete_if_cache
def llm_model_func(
@@ -196,6 +226,7 @@ class LLMClient:
return vision_model_func_via_factory
# OpenAI-compatible bindings
+ # Note: Environment variables are already set in __init__ via _setup_openai_env_vars()
from lightrag.llm.openai import openai_complete_if_cache
# Get api_version once for reuse
diff --git a/src/services/llm/config.py b/src/services/llm/config.py
index e071cc6a7..c11ba6650 100644
--- a/src/services/llm/config.py
+++ b/src/services/llm/config.py
@@ -26,6 +26,37 @@ load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
load_dotenv(PROJECT_ROOT / ".env", override=False)
+def _setup_openai_env_vars_early():
+ """
+ Set OPENAI_API_KEY environment variable early for LightRAG compatibility.
+
+ LightRAG's internal functions (e.g., create_openai_async_client) read directly
+ from os.environ["OPENAI_API_KEY"] instead of using the api_key parameter.
+ This function ensures the environment variable is set as soon as this module
+ is imported, before any LightRAG operations can occur.
+
+ This is called at module load time to ensure env vars are set before any
+ RAG operations, including those in worker threads/processes.
+ """
+ binding = os.getenv("LLM_BINDING", "openai")
+ api_key = os.getenv("LLM_API_KEY")
+ base_url = os.getenv("LLM_HOST")
+
+ # Only set env vars for OpenAI-compatible bindings
+ if binding in ("openai", "azure_openai", "gemini"):
+ if api_key and not os.getenv("OPENAI_API_KEY"):
+ os.environ["OPENAI_API_KEY"] = api_key
+ logger.debug("Set OPENAI_API_KEY env var for LightRAG compatibility (early init)")
+
+ if base_url and not os.getenv("OPENAI_BASE_URL"):
+ os.environ["OPENAI_BASE_URL"] = base_url
+ logger.debug(f"Set OPENAI_BASE_URL env var to {base_url} (early init)")
+
+
+# Execute early setup at module import time
+_setup_openai_env_vars_early()
+
+
@dataclass
class LLMConfig:
"""LLM configuration dataclass."""
diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.py
index fc8467eaa..9c56bc5dc 100644
--- a/src/services/rag/components/indexers/graph.py
+++ b/src/services/rag/components/indexers/graph.py
@@ -51,58 +51,18 @@ class GraphIndexer(BaseComponent):
sys.path.insert(0, str(raganything_path))
try:
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
diff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.py
index 63da12298..2a87a505e 100644
--- a/src/services/rag/components/indexers/lightrag.py
+++ b/src/services/rag/components/indexers/lightrag.py
@@ -53,57 +53,17 @@ class LightRAGIndexer(BaseComponent):
try:
from lightrag import LightRAG
- from openai import AsyncOpenAI
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
# Create pure LightRAG instance (no multimodal)
rag = LightRAG(
diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.py
index a594cb32b..8c1e3137f 100644
--- a/src/services/rag/components/retrievers/hybrid.py
+++ b/src/services/rag/components/retrievers/hybrid.py
@@ -50,58 +50,18 @@ class HybridRetriever(BaseComponent):
sys.path.insert(0, str(raganything_path))
try:
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.py
index c945a3617..334f24861 100644
--- a/src/services/rag/components/retrievers/lightrag.py
+++ b/src/services/rag/components/retrievers/lightrag.py
@@ -52,57 +52,17 @@ class LightRAGRetriever(BaseComponent):
try:
from lightrag import LightRAG
- from openai import AsyncOpenAI
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
# Create pure LightRAG instance (no multimodal)
rag = LightRAG(
diff --git a/src/services/rag/components/routing.py b/src/services/rag/components/routing.py
index 25fcc8d4d..db628dde7 100644
--- a/src/services/rag/components/routing.py
+++ b/src/services/rag/components/routing.py
@@ -284,3 +284,53 @@ class FileTypeRouter:
"""
doc_type = cls.get_document_type(file_path)
return doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN)
+
+ @classmethod
+ def get_extensions_for_provider(cls, provider: str) -> set[str]:
+ """
+ Get supported file extensions for a specific RAG provider.
+
+ Args:
+ provider: RAG provider name (llamaindex, lightrag, raganything)
+
+ Returns:
+ Set of supported file extensions (with leading dot, e.g., {".pdf", ".txt"})
+ """
+ # Base text extensions supported by all providers
+ text_extensions = cls.TEXT_EXTENSIONS.copy()
+
+ if provider == "llamaindex":
+ # LlamaIndex: PDF + all text files (reads any text file directly)
+ return cls.MINERU_EXTENSIONS | text_extensions
+
+ elif provider == "lightrag":
+ # LightRAG: PDF + all text files (uses FileTypeRouter)
+ return cls.MINERU_EXTENSIONS | text_extensions
+
+ elif provider == "raganything":
+ # RAGAnything: PDF + Word + Images + all text files (full multimodal via MinerU)
+ return (
+ cls.MINERU_EXTENSIONS
+ | cls.DOCX_EXTENSIONS
+ | cls.IMAGE_EXTENSIONS
+ | text_extensions
+ )
+
+ else:
+ # Default: same as llamaindex (most conservative)
+ logger.warning(f"Unknown provider '{provider}', using default extensions")
+ return cls.MINERU_EXTENSIONS | text_extensions
+
+ @classmethod
+ def get_glob_patterns_for_provider(cls, provider: str) -> list[str]:
+ """
+ Get glob patterns for file searching based on RAG provider.
+
+ Args:
+ provider: RAG provider name (llamaindex, lightrag, raganything)
+
+ Returns:
+ List of glob patterns (e.g., ["*.pdf", "*.txt", "*.md"])
+ """
+ extensions = cls.get_extensions_for_provider(provider)
+ return [f"*{ext}" for ext in sorted(extensions)]
diff --git a/src/services/rag/factory.py b/src/services/rag/factory.py
index fdf13de91..0516bf952 100644
--- a/src/services/rag/factory.py
+++ b/src/services/rag/factory.py
@@ -9,10 +9,12 @@ from typing import Callable, Dict, List, Optional
from .pipelines import lightrag, llamaindex
from .pipelines.raganything import RAGAnythingPipeline
+from .pipelines.raganything_docling import RAGAnythingDoclingPipeline
# Pipeline registry
_PIPELINES: Dict[str, Callable] = {
"raganything": RAGAnythingPipeline, # Full multimodal: MinerU parser, deep analysis (slow, thorough)
+ "raganything_docling": RAGAnythingDoclingPipeline, # Docling parser: Office/HTML friendly, easier setup
"lightrag": lightrag.LightRAGPipeline, # Knowledge graph: PDFParser, fast text-only (medium speed)
"llamaindex": llamaindex.LlamaIndexPipeline, # Vector-only: Simple chunking, fast (fastest)
}
@@ -41,12 +43,12 @@ def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, *
# Handle different pipeline types:
# - lightrag, academic: functions that return RAGPipeline
- # - llamaindex, raganything: classes that need instantiation
+ # - llamaindex, raganything, raganything_docling: classes that need instantiation
if name in ("lightrag", "academic"):
# LightRAGPipeline and AcademicPipeline are factory functions
return factory(kb_base_dir=kb_base_dir)
- elif name in ("llamaindex", "raganything"):
- # LlamaIndexPipeline and RAGAnythingPipeline are classes
+ elif name in ("llamaindex", "raganything", "raganything_docling"):
+ # LlamaIndexPipeline, RAGAnythingPipeline, and RAGAnythingDoclingPipeline are classes
if kb_base_dir:
kwargs["kb_base_dir"] = kb_base_dir
return factory(**kwargs)
@@ -75,8 +77,13 @@ def list_pipelines() -> List[Dict[str, str]]:
},
{
"id": "raganything",
- "name": "RAG-Anything",
- "description": "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
+ "name": "RAG-Anything (MinerU)",
+ "description": "Multimodal document processing with MinerU parser. Best for academic PDFs with complex equations and formulas.",
+ },
+ {
+ "id": "raganything_docling",
+ "name": "RAG-Anything (Docling)",
+ "description": "Multimodal document processing with Docling parser. Better for Office documents (.docx, .pptx) and HTML. Easier to install.",
},
]
diff --git a/src/services/rag/pipelines/__init__.py b/src/services/rag/pipelines/__init__.py
index 20c7f3297..7274f4492 100644
--- a/src/services/rag/pipelines/__init__.py
+++ b/src/services/rag/pipelines/__init__.py
@@ -9,9 +9,11 @@ from .academic import AcademicPipeline
from .lightrag import LightRAGPipeline
from .llamaindex import LlamaIndexPipeline
from .raganything import RAGAnythingPipeline
+from .raganything_docling import RAGAnythingDoclingPipeline
__all__ = [
"RAGAnythingPipeline",
+ "RAGAnythingDoclingPipeline",
"LightRAGPipeline",
"LlamaIndexPipeline",
"AcademicPipeline",
diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.py
index c072d8884..38dd2363c 100644
--- a/src/services/rag/pipelines/raganything.py
+++ b/src/services/rag/pipelines/raganything.py
@@ -9,11 +9,13 @@ from pathlib import Path
import sys
from typing import Any, Dict, List, Optional
-from lightrag.llm.openai import openai_complete_if_cache
-
from src.logging import get_logger
from src.logging.adapters import LightRAGLogContext
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
class RAGAnythingPipeline:
"""
@@ -71,106 +73,19 @@ class RAGAnythingPipeline:
self._setup_raganything_path()
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly - bypasses LightRAG's response_format handling
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages array
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
-
- # Add history
- messages.extend(history_messages)
-
- # Add current prompt
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters, filter out LightRAG-specific ones
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
-
- def vision_model_func(
- prompt,
- system_prompt=None,
- history_messages=[],
- image_data=None,
- messages=None,
- **kwargs,
- ):
- # Handle multimodal messages
- if messages:
- clean_kwargs = {
- k: v
- for k, v in kwargs.items()
- if k not in ["messages", "prompt", "system_prompt", "history_messages"]
- }
- return openai_complete_if_cache(
- llm_client.config.model,
- prompt="",
- messages=messages,
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- **clean_kwargs,
- )
- if image_data:
- # Build image message
- image_message = {
- "role": "user",
- "content": [
- {"type": "text", "text": prompt},
- {
- "type": "image_url",
- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
- },
- ],
- }
- return openai_complete_if_cache(
- llm_client.config.model,
- prompt="",
- messages=[image_message],
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- **kwargs,
- )
- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
@@ -197,7 +112,15 @@ class RAGAnythingPipeline:
**kwargs,
) -> bool:
"""
- Initialize KB using RAG-Anything's process_document_complete().
+ Initialize KB using RAG-Anything with MinerU parser.
+
+ Processing flow:
+ 1. Parse documents using MinerU (generates content_list with nested image paths)
+ 2. Migrate images to canonical location (kb/images/) and update paths in content_list
+ 3. Insert updated content_list into RAG (now with correct image paths)
+ 4. Clean up temporary parser output directories
+
+ This ensures RAG stores the final image paths, avoiding path mismatches during retrieval.
Uses FileTypeRouter to classify files and route them appropriately:
- PDF files -> MinerU parser (full document analysis)
@@ -212,13 +135,21 @@ class RAGAnythingPipeline:
Returns:
True if successful
"""
+ import json
+
from ..components.routing import FileTypeRouter
+ from ..utils.image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+ )
self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")
kb_dir = Path(self.kb_base_dir) / kb_name
content_list_dir = kb_dir / "content_list"
+ images_dir = kb_dir / "images"
content_list_dir.mkdir(parents=True, exist_ok=True)
+ images_dir.mkdir(parents=True, exist_ok=True)
# Classify files by type
classification = FileTypeRouter.classify_files(file_paths)
@@ -235,19 +166,47 @@ class RAGAnythingPipeline:
total_files = len(classification.needs_mineru) + len(classification.text_files)
idx = 0
+ total_images_migrated = 0
# Process files requiring MinerU (PDF, DOCX, images)
for file_path in classification.needs_mineru:
idx += 1
- self.logger.info(
- f"Processing [{idx}/{total_files}] (MinerU): {Path(file_path).name}"
- )
- await rag.process_document_complete(
+ file_name = Path(file_path).name
+ self.logger.info(f"Processing [{idx}/{total_files}] (MinerU): {file_name}")
+
+ # Step 1: Parse document (without RAG insertion)
+ self.logger.info(" Step 1/3: Parsing document...")
+ content_list, doc_id = await rag.parse_document(
file_path=file_path,
output_dir=str(content_list_dir),
parse_method="auto",
)
+ # Step 2: Migrate images and update paths
+ self.logger.info(" Step 2/3: Migrating images to canonical location...")
+ updated_content_list, num_migrated = await migrate_images_and_update_paths(
+ content_list=content_list,
+ source_base_dir=content_list_dir,
+ target_images_dir=images_dir,
+ batch_size=50,
+ )
+ total_images_migrated += num_migrated
+
+ # Save updated content_list for future reference
+ content_list_file = content_list_dir / f"{Path(file_path).stem}.json"
+ with open(content_list_file, "w", encoding="utf-8") as f:
+ json.dump(updated_content_list, f, ensure_ascii=False, indent=2)
+
+ # Step 3: Insert into RAG with corrected paths
+ self.logger.info(" Step 3/3: Inserting into RAG knowledge graph...")
+ await rag.insert_content_list(
+ content_list=updated_content_list,
+ file_path=file_path,
+ doc_id=doc_id,
+ )
+
+ self.logger.info(f" โœ“ Completed: {file_name}")
+
# Process text files directly (fast path)
for file_path in classification.text_files:
idx += 1
@@ -263,10 +222,17 @@ class RAGAnythingPipeline:
for file_path in classification.unsupported:
self.logger.warning(f"Skipped unsupported file: {Path(file_path).name}")
+ # Clean up temporary parser output directories
+ if total_images_migrated > 0:
+ self.logger.info("Cleaning up temporary parser output directories...")
+ await cleanup_parser_output_dirs(content_list_dir)
+
if extract_numbered_items:
await self._extract_numbered_items(kb_name)
- self.logger.info(f"KB '{kb_name}' initialized successfully")
+ self.logger.info(
+ f"KB '{kb_name}' initialized successfully ({total_images_migrated} images migrated)"
+ )
return True
async def _extract_numbered_items(self, kb_name: str):
diff --git a/src/services/rag/pipelines/raganything_docling.py b/src/services/rag/pipelines/raganything_docling.py
new file mode 100644
index 000000000..306534d5f
--- /dev/null
+++ b/src/services/rag/pipelines/raganything_docling.py
@@ -0,0 +1,368 @@
+"""
+RAGAnything Docling Pipeline
+============================
+
+End-to-end pipeline wrapping RAG-Anything with Docling parser for document processing.
+Uses Docling instead of MinerU for better Office document and HTML support.
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, Dict, List, Optional
+
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
+from src.logging import get_logger
+from src.logging.adapters import LightRAGLogContext
+
+
+class RAGAnythingDoclingPipeline:
+ """
+ RAG-Anything Pipeline with Docling Parser.
+
+ Uses RAG-Anything's complete processing with Docling as the document parser:
+ - Docling document parsing (supports PDF, Office documents, HTML)
+ - LightRAG knowledge graph construction
+ - Hybrid retrieval (hybrid/local/global/naive modes)
+
+ Advantages over MinerU:
+ - Better support for Office documents (.doc, .docx, .ppt, .pptx, .xls, .xlsx)
+ - Native HTML parsing support
+ - Easier installation (no CUDA dependencies)
+
+ Note: For academic PDFs with complex equations and formulas,
+ use RAGAnythingPipeline (MinerU) instead for better accuracy.
+ """
+
+ name = "raganything_docling"
+
+ def __init__(
+ self,
+ kb_base_dir: Optional[str] = None,
+ enable_image_processing: bool = True,
+ enable_table_processing: bool = True,
+ enable_equation_processing: bool = True,
+ ):
+ """
+ Initialize RAGAnything Docling pipeline.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ enable_image_processing: Enable image extraction and processing
+ enable_table_processing: Enable table extraction and processing
+ enable_equation_processing: Enable equation extraction and processing
+ """
+ self.logger = get_logger("RAGAnythingDoclingPipeline")
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent / "data" / "knowledge_bases"
+ )
+ self.enable_image = enable_image_processing
+ self.enable_table = enable_table_processing
+ self.enable_equation = enable_equation_processing
+ self._instances: Dict[str, Any] = {}
+
+ def _setup_raganything_path(self):
+ """Add RAG-Anything to sys.path if available."""
+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent
+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+ if raganything_path.exists() and str(raganything_path) not in sys.path:
+ sys.path.insert(0, str(raganything_path))
+
+ def _get_rag_instance(self, kb_name: str):
+ """Get or create RAGAnything instance with Docling parser."""
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ if working_dir in self._instances:
+ return self._instances[working_dir]
+
+ self._setup_raganything_path()
+
+ from raganything import RAGAnything, RAGAnythingConfig
+
+ from src.services.embedding import get_embedding_client
+ from src.services.llm import get_llm_client
+
+ # Use unified LLM client from src/services/llm
+ llm_client = get_llm_client()
+ embed_client = get_embedding_client()
+
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
+
+ # Configure RAGAnything with Docling parser
+ # Note: content_format should be "auto" or "minerU" because DoclingParser
+ # converts its output to MinerU-compatible format internally
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ parser="docling", # Use Docling instead of MinerU
+ content_format="auto", # Auto-detect format (Docling outputs MinerU-compatible format)
+ enable_image_processing=self.enable_image,
+ enable_table_processing=self.enable_table,
+ enable_equation_processing=self.enable_equation,
+ )
+
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ vision_model_func=vision_model_func,
+ embedding_func=embed_client.get_embedding_func(),
+ )
+
+ self._instances[working_dir] = rag
+ return rag
+
+ async def initialize(
+ self,
+ kb_name: str,
+ file_paths: List[str],
+ extract_numbered_items: bool = True,
+ **kwargs,
+ ) -> bool:
+ """
+ Initialize KB using RAG-Anything with Docling parser.
+
+ Processing flow:
+ 1. Parse documents using Docling (generates content_list with nested image paths)
+ 2. Migrate images to canonical location (kb/images/) and update paths in content_list
+ 3. Insert updated content_list into RAG (now with correct image paths)
+ 4. Clean up temporary parser output directories
+
+ This ensures RAG stores the final image paths, avoiding path mismatches during retrieval.
+
+ Uses FileTypeRouter to classify files and route them appropriately:
+ - PDF files -> Docling parser
+ - Office files (.doc, .docx, .ppt, .pptx) -> Docling parser (direct support)
+ - HTML files -> Docling parser
+ - Text files -> Direct read + LightRAG insert (fast)
+
+ Args:
+ kb_name: Knowledge base name
+ file_paths: List of file paths to process
+ extract_numbered_items: Whether to extract numbered items after processing
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ import json
+
+ from ..components.routing import FileTypeRouter
+ from ..utils.image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+ )
+
+ self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files (Docling parser)")
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+ images_dir = kb_dir / "images"
+ content_list_dir.mkdir(parents=True, exist_ok=True)
+ images_dir.mkdir(parents=True, exist_ok=True)
+
+ # Classify files by type
+ classification = FileTypeRouter.classify_files(file_paths)
+
+ self.logger.info(
+ f"File classification: {len(classification.needs_mineru)} need Docling, "
+ f"{len(classification.text_files)} text files, "
+ f"{len(classification.unsupported)} unsupported"
+ )
+
+ with LightRAGLogContext(scene="knowledge_init"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ total_files = len(classification.needs_mineru) + len(classification.text_files)
+ idx = 0
+ total_images_migrated = 0
+
+ # Process files requiring Docling (PDF, DOCX, images, HTML)
+ for file_path in classification.needs_mineru:
+ idx += 1
+ file_name = Path(file_path).name
+ self.logger.info(
+ f"Processing [{idx}/{total_files}] (Docling): {file_name}"
+ )
+
+ # Step 1: Parse document (without RAG insertion)
+ self.logger.info(f" Step 1/3: Parsing document...")
+ content_list, doc_id = await rag.parse_document(
+ file_path=file_path,
+ output_dir=str(content_list_dir),
+ parse_method="auto",
+ )
+
+ # Step 2: Migrate images and update paths
+ self.logger.info(f" Step 2/3: Migrating images to canonical location...")
+ updated_content_list, num_migrated = await migrate_images_and_update_paths(
+ content_list=content_list,
+ source_base_dir=content_list_dir,
+ target_images_dir=images_dir,
+ batch_size=50,
+ )
+ total_images_migrated += num_migrated
+
+ # Save updated content_list for future reference
+ content_list_file = content_list_dir / f"{Path(file_path).stem}.json"
+ with open(content_list_file, "w", encoding="utf-8") as f:
+ json.dump(updated_content_list, f, ensure_ascii=False, indent=2)
+
+ # Step 3: Insert into RAG with corrected paths
+ self.logger.info(f" Step 3/3: Inserting into RAG knowledge graph...")
+ await rag.insert_content_list(
+ content_list=updated_content_list,
+ file_path=file_path,
+ doc_id=doc_id,
+ )
+
+ self.logger.info(f" โœ“ Completed: {file_name}")
+
+ # Process text files directly (fast path)
+ for file_path in classification.text_files:
+ idx += 1
+ self.logger.info(
+ f"Processing [{idx}/{total_files}] (direct text): {Path(file_path).name}"
+ )
+ content = await FileTypeRouter.read_text_file(file_path)
+ if content.strip():
+ # Insert directly into LightRAG, bypassing parser
+ await rag.lightrag.ainsert(content)
+
+ # Log unsupported files
+ for file_path in classification.unsupported:
+ self.logger.warning(f"Skipped unsupported file: {Path(file_path).name}")
+
+ # Clean up temporary parser output directories
+ if total_images_migrated > 0:
+ self.logger.info("Cleaning up temporary parser output directories...")
+ await cleanup_parser_output_dirs(content_list_dir)
+
+ if extract_numbered_items:
+ await self._extract_numbered_items(kb_name)
+
+ self.logger.info(
+ f"KB '{kb_name}' initialized successfully with Docling parser "
+ f"({total_images_migrated} images migrated)"
+ )
+ return True
+
+ async def _extract_numbered_items(self, kb_name: str):
+ """Extract numbered items using existing extraction logic."""
+ try:
+ import json
+
+ from src.knowledge.extract_numbered_items import (
+ extract_numbered_items_with_llm_async,
+ )
+ from src.services.llm import get_llm_client
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+
+ if not content_list_dir.exists():
+ self.logger.warning("No content_list directory found, skipping extraction")
+ return
+
+ # Load all content list files
+ all_content_items = []
+ for json_file in content_list_dir.glob("*.json"):
+ with open(json_file, "r", encoding="utf-8") as f:
+ content_items = json.load(f)
+ all_content_items.extend(content_items)
+
+ if not all_content_items:
+ self.logger.warning("No content items found for extraction")
+ return
+
+ self.logger.info(
+ f"Extracting numbered items from {len(all_content_items)} content items"
+ )
+
+ llm_client = get_llm_client()
+ items = await extract_numbered_items_with_llm_async(
+ all_content_items,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ )
+
+ # Save numbered items
+ if items:
+ output_file = kb_dir / "numbered_items.json"
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(items, f, ensure_ascii=False, indent=2)
+ self.logger.info(f"Extracted {len(items)} numbered items")
+
+ except ImportError as e:
+ self.logger.warning(f"Could not import extraction module: {e}")
+ except Exception as e:
+ self.logger.error(f"Failed to extract numbered items: {e}")
+
+ async def search(
+ self,
+ query: str,
+ kb_name: str,
+ mode: str = "hybrid",
+ only_need_context: bool = False,
+ **kwargs,
+ ) -> Dict[str, Any]:
+ """
+ Search using RAG-Anything's aquery().
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ mode: Search mode (hybrid, local, global, naive)
+ only_need_context: Whether to only return context without answer
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ with LightRAGLogContext(scene="rag_search"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)
+ answer_str = answer if isinstance(answer, str) else str(answer)
+
+ return {
+ "query": query,
+ "answer": answer_str,
+ "content": answer_str,
+ "mode": mode,
+ "provider": "raganything_docling",
+ }
+
+ async def delete(self, kb_name: str) -> bool:
+ """
+ Delete knowledge base.
+
+ Args:
+ kb_name: Knowledge base name
+
+ Returns:
+ True if successful
+ """
+ import shutil
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ # Remove from cache
+ if working_dir in self._instances:
+ del self._instances[working_dir]
+
+ # Delete directory
+ if kb_dir.exists():
+ shutil.rmtree(kb_dir)
+ self.logger.info(f"Deleted KB '{kb_name}'")
+ return True
+
+ return False
+
diff --git a/src/services/rag/utils/__init__.py b/src/services/rag/utils/__init__.py
new file mode 100644
index 000000000..694b99d5c
--- /dev/null
+++ b/src/services/rag/utils/__init__.py
@@ -0,0 +1,17 @@
+"""
+RAG Utilities
+=============
+
+Utility modules for RAG operations.
+"""
+
+from .image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+)
+
+__all__ = [
+ "migrate_images_and_update_paths",
+ "cleanup_parser_output_dirs",
+]
+
diff --git a/src/services/rag/utils/image_migration.py b/src/services/rag/utils/image_migration.py
new file mode 100644
index 000000000..2785aa207
--- /dev/null
+++ b/src/services/rag/utils/image_migration.py
@@ -0,0 +1,296 @@
+"""
+Image Migration Utilities
+=========================
+
+Utilities for migrating images from parser output directories to the canonical
+knowledge base images directory, and updating content_list paths accordingly.
+
+This is needed because:
+1. Parsers (MinerU/Docling) output images to nested directories like:
+ content_list/{doc}/auto/images/ or content_list/{doc}/docling/images/
+2. RAG stores these paths in chunks, so if we move files later, retrieval breaks
+3. By migrating images BEFORE RAG indexing, we ensure correct paths are stored
+"""
+
+import asyncio
+import shutil
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+from concurrent.futures import ThreadPoolExecutor
+
+from src.logging import get_logger
+
+logger = get_logger("ImageMigration")
+
+# Maximum concurrent file operations to avoid overwhelming I/O
+MAX_CONCURRENT_COPIES = 10
+
+
+async def migrate_images_and_update_paths(
+ content_list: List[Dict[str, Any]],
+ source_base_dir: Path,
+ target_images_dir: Path,
+ batch_size: int = 50,
+) -> Tuple[List[Dict[str, Any]], int]:
+ """
+ Migrate images from parser output to canonical images directory and update paths.
+
+ This function:
+ 1. Scans content_list for image paths
+ 2. Copies images to target_images_dir (with deduplication)
+ 3. Updates content_list with new paths
+ 4. Returns updated content_list
+
+ Args:
+ content_list: Parsed content list from MinerU/Docling
+ source_base_dir: Base directory where parser outputs are located
+ target_images_dir: Canonical images directory (e.g., kb/images/)
+ batch_size: Number of images to process in each batch
+
+ Returns:
+ Tuple of (updated_content_list, num_images_migrated)
+ """
+ # Ensure target directory exists
+ target_images_dir.mkdir(parents=True, exist_ok=True)
+
+ # Collect all image items that need migration
+ image_items = []
+ for idx, item in enumerate(content_list):
+ if not isinstance(item, dict):
+ continue
+
+ # Check for image path in various fields
+ img_path = item.get("img_path") or item.get("image_path")
+ if img_path:
+ image_items.append((idx, img_path, "img_path" if "img_path" in item else "image_path"))
+
+ if not image_items:
+ logger.debug("No images found in content_list, skipping migration")
+ return content_list, 0
+
+ logger.info(f"Found {len(image_items)} images to migrate")
+
+ # Process images in batches to handle large quantities
+ migrated_count = 0
+ path_updates = {} # old_path -> new_path mapping
+
+ for batch_start in range(0, len(image_items), batch_size):
+ batch = image_items[batch_start:batch_start + batch_size]
+ batch_updates = await _process_image_batch(
+ batch, source_base_dir, target_images_dir
+ )
+ path_updates.update(batch_updates)
+ migrated_count += len([v for v in batch_updates.values() if v])
+
+ if batch_start + batch_size < len(image_items):
+ logger.info(f"Migrated {batch_start + len(batch)}/{len(image_items)} images...")
+
+ # Update content_list with new paths
+ updated_content_list = _update_content_list_paths(content_list, path_updates)
+
+ logger.info(f"Image migration complete: {migrated_count} images migrated")
+ return updated_content_list, migrated_count
+
+
+async def _process_image_batch(
+ batch: List[Tuple[int, str, str]],
+ source_base_dir: Path,
+ target_images_dir: Path,
+) -> Dict[str, str]:
+ """
+ Process a batch of images concurrently.
+
+ Args:
+ batch: List of (index, image_path, field_name) tuples
+ source_base_dir: Base directory for resolving relative paths
+ target_images_dir: Target directory for images
+
+ Returns:
+ Dict mapping old paths to new paths
+ """
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_COPIES)
+
+ async def copy_single_image(idx: int, img_path: str, field_name: str) -> Tuple[str, str]:
+ async with semaphore:
+ return await _migrate_single_image(
+ img_path, source_base_dir, target_images_dir
+ )
+
+ tasks = [
+ copy_single_image(idx, img_path, field_name)
+ for idx, img_path, field_name in batch
+ ]
+
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ path_updates = {}
+ for result in results:
+ if isinstance(result, Exception):
+ logger.warning(f"Error migrating image: {result}")
+ continue
+ old_path, new_path = result
+ if new_path:
+ path_updates[old_path] = new_path
+
+ return path_updates
+
+
+async def _migrate_single_image(
+ img_path: str,
+ source_base_dir: Path,
+ target_images_dir: Path,
+) -> Tuple[str, str]:
+ """
+ Migrate a single image file.
+
+ Args:
+ img_path: Original image path (may be absolute or relative)
+ source_base_dir: Base directory for resolving relative paths
+ target_images_dir: Target directory for images
+
+ Returns:
+ Tuple of (original_path, new_path) or (original_path, None) if failed
+ """
+ try:
+ # Resolve the source path
+ source_path = Path(img_path)
+ if not source_path.is_absolute():
+ source_path = source_base_dir / img_path
+
+ if not source_path.exists():
+ logger.warning(f"Source image not found: {img_path}")
+ return (img_path, None)
+
+ # Generate target filename (preserve original name)
+ target_filename = source_path.name
+ target_path = target_images_dir / target_filename
+
+ # Handle filename conflicts by adding suffix
+ if target_path.exists():
+ # Check if it's the same file (by size)
+ if target_path.stat().st_size == source_path.stat().st_size:
+ # Same file already exists, just update path
+ return (img_path, str(target_path))
+
+ # Different file with same name, add suffix
+ stem = source_path.stem
+ suffix = source_path.suffix
+ counter = 1
+ while target_path.exists():
+ target_filename = f"{stem}_{counter}{suffix}"
+ target_path = target_images_dir / target_filename
+ counter += 1
+
+ # Copy file using thread pool to avoid blocking
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ shutil.copy2,
+ str(source_path),
+ str(target_path)
+ )
+
+ logger.debug(f"Migrated: {source_path.name} -> {target_path}")
+ return (img_path, str(target_path))
+
+ except Exception as e:
+ logger.error(f"Failed to migrate image {img_path}: {e}")
+ return (img_path, None)
+
+
+def _update_content_list_paths(
+ content_list: List[Dict[str, Any]],
+ path_updates: Dict[str, str],
+) -> List[Dict[str, Any]]:
+ """
+ Update image paths in content_list with new paths.
+
+ Args:
+ content_list: Original content list
+ path_updates: Mapping of old paths to new paths
+
+ Returns:
+ Updated content list (new list, original is not modified)
+ """
+ updated_list = []
+
+ for item in content_list:
+ if not isinstance(item, dict):
+ updated_list.append(item)
+ continue
+
+ # Create a copy of the item
+ updated_item = dict(item)
+
+ # Update img_path if present
+ if "img_path" in updated_item:
+ old_path = updated_item["img_path"]
+ if old_path in path_updates and path_updates[old_path]:
+ updated_item["img_path"] = path_updates[old_path]
+
+ # Update image_path if present (alternative field name)
+ if "image_path" in updated_item:
+ old_path = updated_item["image_path"]
+ if old_path in path_updates and path_updates[old_path]:
+ updated_item["image_path"] = path_updates[old_path]
+
+ updated_list.append(updated_item)
+
+ return updated_list
+
+
+async def cleanup_parser_output_dirs(
+ content_list_dir: Path,
+ parser_subdirs: List[str] = None,
+) -> int:
+ """
+ Clean up parser output directories after successful migration.
+
+ Only removes the nested parser output directories (auto/, docling/),
+ NOT the content_list JSON files at the root level.
+
+ Args:
+ content_list_dir: The content_list directory
+ parser_subdirs: List of parser subdirectory names to clean
+
+ Returns:
+ Number of directories cleaned up
+ """
+ if parser_subdirs is None:
+ parser_subdirs = ["auto", "docling"]
+
+ cleaned_count = 0
+
+ for doc_dir in content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Run in thread pool to avoid blocking
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ shutil.rmtree,
+ str(subdir)
+ )
+ cleaned_count += 1
+ logger.debug(f"Cleaned up: {subdir}")
+ except Exception as e:
+ logger.warning(f"Failed to clean up {subdir}: {e}")
+
+ # Remove the doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ logger.debug(f"Removed empty directory: {doc_dir}")
+ except Exception as e:
+ logger.debug(f"Could not remove directory {doc_dir}: {e}")
+
+ if cleaned_count > 0:
+ logger.info(f"Cleaned up {cleaned_count} parser output directories")
+
+ return cleaned_count
+
diff --git a/tests/services/rag/testfile.html b/tests/services/rag/testfile.html
new file mode 100644
index 000000000..960f0af19
--- /dev/null
+++ b/tests/services/rag/testfile.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>ๆทฑๅบฆๅญฆไน ๅŸบ็ก€ - ๆต‹่ฏ•ๆ–‡ๆกฃ</title>
+</head>
+<body>
+ <header>
+ <h1>ๆทฑๅบฆๅญฆไน ๅŸบ็ก€ๆ•™็จ‹</h1>
+ <p>ๆœฌๆ–‡ๆกฃ็”จไบŽRAG็ฎก้“ๆต‹่ฏ•</p>
+ </header>
+
+ <main>
+ <article>
+ <h2>ไป€ไนˆๆ˜ฏๆทฑๅบฆๅญฆไน ๏ผŸ</h2>
+ <p>ๆทฑๅบฆๅญฆไน ๏ผˆDeep Learning๏ผ‰ๆ˜ฏๆœบๅ™จๅญฆไน ็š„ไธ€ไธชๅˆ†ๆ”ฏ๏ผŒๅฎƒไฝฟ็”จๅคšๅฑ‚็ฅž็ป็ฝ‘็ปœๆฅๅญฆไน ๆ•ฐๆฎ็š„ๅฑ‚ๆฌกๅŒ–่กจ็คบใ€‚ๆทฑๅบฆๅญฆไน ๅœจๅ›พๅƒ่ฏ†ๅˆซใ€่‡ช็„ถ่ฏญ่จ€ๅค„็†ๅ’Œ่ฏญ้Ÿณ่ฏ†ๅˆซ็ญ‰้ข†ๅŸŸๅ–ๅพ—ไบ†็ช็ ดๆ€ง่ฟ›ๅฑ•ใ€‚</p>
+
+ <h3>็ฅž็ป็ฝ‘็ปœ็š„ๅŸบๆœฌ็ป„ๆˆ</h3>
+ <ul>
+ <li><strong>่พ“ๅ…ฅๅฑ‚</strong>๏ผšๆŽฅๆ”ถๅŽŸๅง‹ๆ•ฐๆฎ</li>
+ <li><strong>้š่—ๅฑ‚</strong>๏ผš่ฟ›่กŒ็‰นๅพๆๅ–ๅ’Œ่ฝฌๆข</li>
+ <li><strong>่พ“ๅ‡บๅฑ‚</strong>๏ผšไบง็”Ÿๆœ€็ปˆ้ข„ๆต‹็ป“ๆžœ</li>
+ </ul>
+
+ <h3>ๅธธ่ง็š„ๆทฑๅบฆๅญฆไน ๆจกๅž‹</h3>
+ <table border="1">
+ <thead>
+ <tr>
+ <th>ๆจกๅž‹็ฑปๅž‹</th>
+ <th>ไธป่ฆๅบ”็”จ</th>
+ <th>็‰น็‚น</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>ๅท็งฏ็ฅž็ป็ฝ‘็ปœ (CNN)</td>
+ <td>ๅ›พๅƒๅˆ†็ฑปใ€็›ฎๆ ‡ๆฃ€ๆต‹</td>
+ <td>ๅฑ€้ƒจๆ„Ÿๅ—้‡Žใ€ๅ‚ๆ•ฐๅ…ฑไบซ</td>
+ </tr>
+ <tr>
+ <td>ๅพช็Žฏ็ฅž็ป็ฝ‘็ปœ (RNN)</td>
+ <td>ๅบๅˆ—ๅปบๆจกใ€ๆ—ถ้—ดๅบๅˆ—้ข„ๆต‹</td>
+ <td>ๅค„็†ๅ˜้•ฟๅบๅˆ—ใ€่ฎฐๅฟ†ๅŠŸ่ƒฝ</td>
+ </tr>
+ <tr>
+ <td>Transformer</td>
+ <td>่‡ช็„ถ่ฏญ่จ€ๅค„็†ใ€ๅคง่ฏญ่จ€ๆจกๅž‹</td>
+ <td>่‡ชๆณจๆ„ๅŠ›ๆœบๅˆถใ€ๅนถ่กŒ่ฎก็ฎ—</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <h2>ๆทฑๅบฆๅญฆไน ็š„่ฎญ็ปƒ่ฟ‡็จ‹</h2>
+ <ol>
+ <li>ๆ•ฐๆฎ้ข„ๅค„็†๏ผšๆธ…ๆด—ใ€ๅฝ’ไธ€ๅŒ–ใ€ๆ•ฐๆฎๅขžๅผบ</li>
+ <li>ๅ‰ๅ‘ไผ ๆ’ญ๏ผš่ฎก็ฎ—้ข„ๆต‹ๅ€ผ</li>
+ <li>ๆŸๅคฑ่ฎก็ฎ—๏ผšๆฏ”่พƒ้ข„ๆต‹ๅ€ผไธŽ็œŸๅฎžๅ€ผ</li>
+ <li>ๅๅ‘ไผ ๆ’ญ๏ผš่ฎก็ฎ—ๆขฏๅบฆ</li>
+ <li>ๅ‚ๆ•ฐๆ›ดๆ–ฐ๏ผšไฝฟ็”จไผ˜ๅŒ–ๅ™จๆ›ดๆ–ฐๆƒ้‡</li>
+ </ol>
+
+ <h3>ๅธธ็”จๆฟ€ๆดปๅ‡ฝๆ•ฐ</h3>
+ <p>ๆฟ€ๆดปๅ‡ฝๆ•ฐไธบ็ฅž็ป็ฝ‘็ปœๅผ•ๅ…ฅ้ž็บฟๆ€ง๏ผŒๅธธ็”จ็š„ๆฟ€ๆดปๅ‡ฝๆ•ฐๅŒ…ๆ‹ฌ๏ผš</p>
+ <ul>
+ <li><code>ReLU</code>: f(x) = max(0, x)</li>
+ <li><code>Sigmoid</code>: f(x) = 1 / (1 + e^(-x))</li>
+ <li><code>Tanh</code>: f(x) = (e^x - e^(-x)) / (e^x + e^(-x))</li>
+ <li><code>Softmax</code>: ็”จไบŽๅคšๅˆ†็ฑป้—ฎ้ข˜็š„่พ“ๅ‡บๅฑ‚</li>
+ </ul>
+
+ <blockquote>
+ <p>"ๆทฑๅบฆๅญฆไน ็š„ๆˆๅŠŸๅœจไบŽๅ…ถ่ƒฝๅคŸ่‡ชๅŠจๅญฆไน ็‰นๅพ่กจ็คบ๏ผŒ่€Œๆ— ้œ€ไบบๅทฅ่ฎพ่ฎก็‰นๅพใ€‚"</p>
+ <footer>โ€”โ€” Yann LeCun, Geoffrey Hinton, Yoshua Bengio</footer>
+ </blockquote>
+ </article>
+
+ <aside>
+ <h3>็›ธๅ…ณ่ต„ๆบ</h3>
+ <nav>
+ <ul>
+ <li><a href="https://pytorch.org">PyTorch ๅฎ˜ๆ–นๆ–‡ๆกฃ</a></li>
+ <li><a href="https://tensorflow.org">TensorFlow ๅฎ˜ๆ–นๆ–‡ๆกฃ</a></li>
+ <li><a href="https://keras.io">Keras ๆ•™็จ‹</a></li>
+ </ul>
+ </nav>
+ </aside>
+ </main>
+
+ <footer>
+ <p>ยฉ 2024 DeepTutor ๆต‹่ฏ•ๆ–‡ไปถ | ไป…็”จไบŽๅ•ๅ…ƒๆต‹่ฏ•</p>
+ </footer>
+</body>
+</html>
+
diff --git a/web/.env.local b/web/.env.local
index 8840a64d6..0b6543af3 100644
--- a/web/.env.local
+++ b/web/.env.local
@@ -3,7 +3,7 @@
# ============================================
# This file is automatically updated based on config/main.yaml
# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)
-#
+#
# To configure for remote access, set in your .env file:
# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001
# ============================================
diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsx
index ca8c8b145..de541b77a 100644
--- a/web/app/knowledge/page.tsx
+++ b/web/app/knowledge/page.tsx
@@ -29,7 +29,7 @@ interface FileSystemDirectoryReader {
declare global {
interface DataTransferItem {
- webkitGetAsEntry(): FileSystemEntry | null;
+ webkitGetAsEntry?(): FileSystemEntry | null;
}
}
import {
@@ -121,28 +121,101 @@ export default function KnowledgePage() {
return parts.length > 1 ? parts.pop()?.toLowerCase() || "" : "";
};
- // Supported file extensions (matching backend DocumentValidator.ALLOWED_EXTENSIONS)
- const SUPPORTED_EXTENSIONS = [
- "pdf",
- "txt",
- "md", // Documents
- "doc",
- "docx",
- "rtf", // Word documents
- "html",
- "htm",
- "xml",
- "json", // Web/Data formats
- "csv",
- "xlsx",
- "xls", // Spreadsheets
- "pptx",
- "ppt", // Presentations
- ];
+ // Supported file extensions per RAG provider (based on actual backend capabilities)
+ const PROVIDER_SUPPORTED_EXTENSIONS: Record<string, string[]> = {
+ // LlamaIndex: PDF + plain text files only (uses PyMuPDF for PDF, direct read for text)
+ llamaindex: [
+ "pdf",
+ "txt",
+ "md",
+ "markdown",
+ "json",
+ "csv",
+ "html",
+ "htm",
+ "xml",
+ "yaml",
+ "yml",
+ "toml",
+ "tex",
+ "rst",
+ "log",
+ ],
+ // LightRAG: Same as LlamaIndex - PDF + plain text files (uses FileTypeRouter + PDFParser)
+ lightrag: [
+ "pdf",
+ "txt",
+ "md",
+ "markdown",
+ "json",
+ "csv",
+ "html",
+ "htm",
+ "xml",
+ "yaml",
+ "yml",
+ "toml",
+ "tex",
+ "rst",
+ "log",
+ ],
+ // RAGAnything: Full multimodal support - PDF, Word, Images, and plain text (uses MinerU)
+ raganything: [
+ "pdf",
+ "doc",
+ "docx",
+ "txt",
+ "md",
+ "markdown",
+ "json",
+ "csv",
+ "html",
+ "htm",
+ "xml",
+ "yaml",
+ "yml",
+ "toml",
+ "tex",
+ "rst",
+ "log",
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "webp",
+ "bmp",
+ "tiff",
+ "tif",
+ ],
+ };
+
+ // Human-readable file type hints for each provider
+ const PROVIDER_FILE_HINTS: Record<string, string> = {
+ llamaindex: "PDF, TXT, MD, JSON, CSV, HTML, XML...",
+ lightrag: "PDF, TXT, MD, JSON, CSV, HTML, XML...",
+ raganything: "PDF, Word, ๅ›พ็‰‡, TXT, MD, JSON, CSV, HTML...",
+ };
+
+ // Get supported extensions for current provider
+ const getSupportedExtensions = (provider: string): string[] => {
+ return PROVIDER_SUPPORTED_EXTENSIONS[provider] || PROVIDER_SUPPORTED_EXTENSIONS.llamaindex;
+ };
+
+ // Get file type hint for current provider
+ const getFileTypeHint = (provider: string): string => {
+ return PROVIDER_FILE_HINTS[provider] || PROVIDER_FILE_HINTS.llamaindex;
+ };
+
+ // Get accept attribute for file input based on provider
+ const getAcceptAttribute = (provider: string): string => {
+ const extensions = getSupportedExtensions(provider);
+ return extensions.map((ext) => `.${ext}`).join(",");
+ };
const isSupportedFile = (filename: string): boolean => {
const ext = getFileExtension(filename);
- return SUPPORTED_EXTENSIONS.includes(ext);
+ const supportedExtensions = getSupportedExtensions(ragProvider);
+ return supportedExtensions.includes(ext);
};
// Helper function to convert File to UploadFile
@@ -789,7 +862,9 @@ export default function KnowledgePage() {
});
if (!res.ok) {
const errorData = await res.json();
- throw new Error(errorData.detail || "Creation failed");
+ showToast(errorData.detail || "Creation failed", "error");
+ setUploading(false);
+ return;
}
const result = await res.json();
@@ -1343,7 +1418,7 @@ export default function KnowledgePage() {
}
e.target.value = ""; // Reset input to allow re-selecting same files
}}
- accept=".pdf,.txt,.md,.doc,.docx,.rtf,.html,.htm,.xml,.json,.csv,.xlsx,.xls,.pptx,.ppt"
+ accept={getAcceptAttribute(ragProvider)}
/>
{/* Drop zone / Click to upload area */}
@@ -1360,7 +1435,7 @@ export default function KnowledgePage() {
: "Drag & drop files or folders here"}
</span>
<span className="text-xs text-slate-400 dark:text-slate-500">
- PDF, Word, Excel, PPT, TXT, MD, HTML, CSV, JSON...
+ {getFileTypeHint(ragProvider)}
</span>
</label>
@@ -1549,7 +1624,7 @@ export default function KnowledgePage() {
}
e.target.value = ""; // Reset input to allow re-selecting same files
}}
- accept=".pdf,.txt,.md,.doc,.docx,.rtf,.html,.htm,.xml,.json,.csv,.xlsx,.xls,.pptx,.ppt"
+ accept={getAcceptAttribute(ragProvider)}
/>
{/* Drop zone / Click to upload area */}
@@ -1566,7 +1641,7 @@ export default function KnowledgePage() {
: "Drag & drop files or folders here"}
</span>
<span className="text-xs text-slate-400 dark:text-slate-500">
- PDF, Word, Excel, PPT, TXT, MD, HTML, CSV, JSON...
+ {getFileTypeHint(ragProvider)}
</span>
</label>
diff --git a/web/app/settings/components/ConfigForm.tsx b/web/app/settings/components/ConfigForm.tsx
index de398cd93..e4b0d329e 100644
--- a/web/app/settings/components/ConfigForm.tsx
+++ b/web/app/settings/components/ConfigForm.tsx
@@ -432,8 +432,8 @@ export default function ConfigForm({
</label>
<input
type="number"
- value={dimensions}
- onChange={(e) => setDimensions(parseInt(e.target.value))}
+ value={Number.isNaN(dimensions) ? "" : dimensions}
+ onChange={(e) => setDimensions(parseInt(e.target.value, 10))}
className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>