Skip to content

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

feat: enhance RAG pipeline with Docling support and improve CI/CD workflows

Bingxi Zhaob3f511d45f1a
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index fbbf2c44b..2d2cde558 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,9 +34,6 @@ jobs:
contents: read
packages: write
- outputs:
- digest: ${{ steps.build.outputs.digest }}
-
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -80,7 +77,6 @@ jobs:
type=ref,event=tag
- name: Build and push AMD64 image
- id: build
uses: docker/build-push-action@v6
with:
context: .
@@ -94,7 +90,6 @@ jobs:
cache-to: type=gha,mode=max,scope=amd64
build-args: |
BACKEND_PORT=8001
- provenance: false
# ============================================
# Build ARM64 Image (Apple Silicon, ARM servers)
@@ -107,9 +102,6 @@ jobs:
contents: read
packages: write
- outputs:
- digest: ${{ steps.build.outputs.digest }}
-
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -156,7 +148,6 @@ 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: .
@@ -170,42 +161,6 @@ 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
@@ -214,22 +169,14 @@ jobs:
name: Generate Summary
runs-on: ubuntu-latest
needs: [build-amd64, build-arm64]
- if: always()
steps:
- name: Generate image summary
run: |
- echo "## 🐳 Docker Images Build Summary" >> $GITHUB_STEP_SUMMARY
+ echo "## 🐳 Docker Images Published" >> $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 2585a1f29..1ae50f868 100644
--- a/.github/workflows/linting.yaml
+++ b/.github/workflows/linting.yaml
@@ -11,11 +11,8 @@ on:
- develop
jobs:
- # ============================================
- # Python Linting with pre-commit
- # ============================================
- python-lint:
- name: Python Linting
+ lint-and-format:
+ name: Linting and Formatting
runs-on: ubuntu-latest
steps:
@@ -25,7 +22,14 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v5
with:
- python-version: "3.10"
+ 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
- name: Cache pre-commit
uses: actions/cache@v4
@@ -35,14 +39,19 @@ jobs:
restore-keys: |
pre-commit-
- - name: Install pre-commit
+ - name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install pre-commit
- - name: Run pre-commit on Python files
+ - name: Install frontend dependencies
+ working-directory: ./web
+ run: npm ci
+
+ - name: Run pre-commit
run: |
- echo "πŸ” Running pre-commit hooks on Python files..."
+ # Show which hooks will run
+ echo "Running pre-commit hooks..."
pre-commit run --all-files --verbose 2>&1 || {
echo ""
echo "╔═══════════════════════════════════════════════════════════════════════════╗"
@@ -62,84 +71,3 @@ 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 75e7ac56f..cf492e4ce 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -22,33 +22,20 @@ on:
- "pyproject.toml"
jobs:
- # ============================================
- # Import Check - Quick validation across Python versions
- # ============================================
+ # Quick import check to ensure modules load correctly
+ # Uses minimal dependencies to avoid disk space issues
import-check:
- name: Import Check (Python ${{ matrix.python-version }})
+ name: Import Check
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 ${{ matrix.python-version }}
+ - name: Set up Python
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 }}-
+ python-version: "3.10"
- name: Install minimal dependencies for import check
run: |
@@ -72,7 +59,6 @@ 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')"
@@ -80,82 +66,3 @@ 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 45fb3e8e6..fddadb68c 100644
--- a/.github/workflows/update-roster.yml
+++ b/.github/workflows/update-roster.yml
@@ -1,9 +1,9 @@
name: Update Repo Roster
on:
- # Run once a day (at 00:00 UTC)
+ # Run twice a day (at 00:00 and 12:00 UTC)
schedule:
- - cron: '0 0 * * *'
+ - cron: '0 0,12 * * *'
# Allow manual trigger
workflow_dispatch:
# Run when stars/forks might change (on push to main)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e21601473..3c2e5b052 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -88,6 +88,16 @@ repos:
args: [-c, pyproject.toml, -q]
exclude: ^tests/
+ # ============================================
+ # Docstring coverage checking
+ # ============================================
+ - repo: https://github.com/econchick/interrogate
+ rev: 1.7.0
+ hooks:
+ - id: interrogate
+ args: [-v, -q, --exclude=tests/, --exclude=scripts/, --ignore-init-method, --ignore-private]
+ pass_filenames: false
+
# ============================================
# Type checking
# ============================================
diff --git a/README.md b/README.md
index a9d4fedc5..2f684110d 100644
--- a/README.md
+++ b/README.md
@@ -37,8 +37,6 @@
---
### πŸ“° News
-> **[2026.1.15]** DeepTutor [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) is out! Fixed multiple environment configuration and stability issues. We recommend everyone to pull the latest version! πŸŽ‰
-
> **[2026.1.1]** Happy New Year! Join our [Discord Community](https://discord.gg/zpP9cssj), [Wechat Community](https://github.com/HKUDS/DeepTutor/issues/78), or [Discussions](https://github.com/HKUDS/DeepTutor/discussions) - shape the future of DeepTutor! πŸ’¬
> **[2025.12.30]** Visit our [Official Website](https://hkuds.github.io/DeepTutor/) for more details!
@@ -47,10 +45,13 @@
### πŸ“¦ Releases
-> **[2026.1.15]** Release [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) - Unified LLM & Embedding services, RAG pipeline selection, and major enhancements to Home, History, QuestionGen & Settings modules -- Thanks to all the contributors!
+> **[2026.1.18]** Release [v0.5.1](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.1) - Enhance RAG pipeline with Docling support and improve CI/CD workflows with several minor bugs fixed -- Thanks to all the feedbacks!
+
<details>
<summary>History releases</summary>
+> **[2026.1.15]** Release [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) - Unified LLM & Embedding services, RAG pipeline selection, and major enhancements to Home, History, QuestionGen & Settings modules -- Thanks to all the contributors!
+
> **[2026.1.9]** Release [v0.4.1](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.1) with LLM Provider system overhaul, Question Generation robustness improvements, and codebase cleanup - Thanks to all the contributors!
> **[2026.1.9]** Release [v0.4.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.4.0) with new code structure, multiple llm & embeddings support - Thanks to all the contributors!
diff --git a/config/main.yaml b/config/main.yaml
index 6db5d8b5c..619523a19 100644
--- a/config/main.yaml
+++ b/config/main.yaml
@@ -28,15 +28,16 @@ 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
- # RAG module logger name mapping (optional customization)
- rag_logger_names:
- knowledge_init: RAG-Init
- rag_tool: RAG
+ lightrag_forwarding:
+ enabled: true
+ min_level: DEBUG
+ add_prefix: true
+ logger_names:
+ knowledge_init: LightRAG-Init
+ rag_tool: LightRAG
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 a8e5bca34..953f38be1 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -35,7 +35,8 @@ services:
environment:
- NODE_ENV=development
- # Logging: Configure in config/main.yaml -> logging.level
+ # Enable more verbose logging in development
+ - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-DEBUG}
# 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 b7a3c0bb9..f05c788cc 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -57,7 +57,8 @@ services:
# Web Search Configuration (Optional)
- SEARCH_PROVIDER=${SEARCH_PROVIDER:-perplexity}
- SEARCH_API_KEY=${SEARCH_API_KEY:-}
- # Logging: Configure in config/main.yaml -> logging.level
+ # Logging Configuration
+ - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-INFO}
# ============================================
# Service Ports Configuration
# ============================================
diff --git a/requirements.txt b/requirements.txt
index 8ecf5e36e..6047daedc 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -44,7 +44,6 @@ 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
deleted file mode 100644
index 5680e9f46..000000000
--- a/scripts/check_install.py
+++ /dev/null
@@ -1,461 +0,0 @@
-#!/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 bcd40ba70..e3ce35996 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 llama-index
- print_info("Stage 2/3: Installing llama-index...")
+ # Stage 2: Install lightrag-hku
+ print_info("Stage 2/3: Installing lightrag-hku...")
try:
- cmd = [sys.executable, "-m", "pip", "install", "llama-index>=0.14.12"]
+ cmd = [sys.executable, "-m", "pip", "install", "lightrag-hku>=1.0.0"]
result = subprocess.run(
cmd,
check=False,
@@ -158,14 +158,12 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
text=True,
)
if result.returncode != 0:
- print_warning("llama-index installation had issues, continuing...")
+ print_warning("lightrag-hku installation had issues, continuing...")
except Exception as e:
- print_warning(f"llama-index installation error: {e}")
+ print_warning(f"lightrag-hku installation error: {e}")
- # Stage 3: Install raganything (includes lightrag-hku as dependency)
- print_info(
- "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
- )
+ # Stage 3: Install raganything with special handling
+ print_info("Stage 3/3: Installing raganything (this may take a while)...")
try:
# First try normal install
cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0"]
@@ -194,23 +192,6 @@ 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"]
@@ -540,15 +521,7 @@ 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",
- "llama_index",
- "docling",
- ]
+ backend_packages = ["fastapi", "uvicorn", "openai", "lightrag_hku", "raganything"]
for package in backend_packages:
try:
@@ -557,18 +530,12 @@ 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:
- 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
+ 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 ae6afe229..7e6fb6012 100644
--- a/scripts/install_all.sh
+++ b/scripts/install_all.sh
@@ -129,21 +129,17 @@ install_with_pip_staged() {
return 1
fi
- # 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 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 3: raganything (includes lightrag-hku as dependency)
- print_info "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
+ # Stage 3: raganything (complex dependencies)
+ print_info "Stage 3/3: Installing raganything (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
@@ -347,21 +343,6 @@ 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 dd5ba6b61..2884c2275 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 66ee5072e..e13763ed8 100644
--- a/src/api/main.py
+++ b/src/api/main.py
@@ -23,7 +23,6 @@ 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 = (
@@ -131,17 +130,6 @@ 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 e21b62654..a42ddf7b5 100644
--- a/src/config/constants.py
+++ b/src/config/constants.py
@@ -23,14 +23,12 @@ VALID_SOLVE_TOOLS = [
"finish",
]
-# Standard log level tags (used in unified logging format)
-LOG_LEVEL_TAGS = [
- "DEBUG",
- "INFO",
- "SUCCESS",
- "WARNING",
- "ERROR",
- "CRITICAL",
- "PROGRESS",
- "COMPLETE",
-]
+# Logging symbols for different log levels
+LOG_SYMBOLS = {
+ "DEBUG": "Β·",
+ "INFO": "●",
+ "SUCCESS": "βœ“",
+ "WARNING": "⚠",
+ "ERROR": "βœ—",
+ "CRITICAL": "βœ—",
+}
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
index 7e8cdfeb6..bb7ff46da 100644
--- a/src/knowledge/add_documents.py
+++ b/src/knowledge/add_documents.py
@@ -21,15 +21,13 @@ 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:
- # This will be caught during runtime if needed
+ # These will be caught during runtime if needed
+ openai_complete_if_cache = None
EmbeddingFunc = None
# Type hinting support for dynamic imports
@@ -221,16 +219,99 @@ class DocumentAdder:
if self.progress_tracker:
from src.knowledge.progress_tracker import ProgressStage
- # Use unified LLM client from src/services/llm
- from src.services.llm import get_llm_client
+ 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,
+ )
- llm_client = get_llm_client()
- self.llm_cfg = llm_client.config
+ # 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,
+ )
- # 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()
+ # --- 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,
+ )
# Embedding Setup
reset_embedding_client()
@@ -383,50 +464,36 @@ class DocumentAdder:
]
async def fix_structure(self):
- """
- Clean up parser output directories after image migration.
+ """Robustly moves nested outputs and cleans up."""
+ logger.info("Organizing storage structure...")
- 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("*")):
+ # 1. Identify moves
+ moves = []
+ for doc_dir in self.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:
- # 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")
+ # 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)
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 0fb6abf15..aa2111942 100644
--- a/src/knowledge/extract_numbered_items.py
+++ b/src/knowledge/extract_numbered_items.py
@@ -19,8 +19,9 @@ 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_client, get_llm_config
+from src.services.llm import get_llm_config
load_dotenv(dotenv_path=".env", override=False)
@@ -61,18 +62,18 @@ async def _call_llm_async(
temperature: float = 0.1,
model: str = None,
) -> str:
- """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
+ """Asynchronously call LLM"""
+ # If model not specified, get from env_config
if model is None:
- model = llm_client.config.model
+ llm_cfg = get_llm_config()
+ model = llm_cfg.model
- result = llm_model_func(
+ result = openai_complete_if_cache(
+ model,
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 3dfc18f46..2ed8deef7 100644
--- a/src/knowledge/initializer.py
+++ b/src/knowledge/initializer.py
@@ -274,58 +274,80 @@ class KnowledgeBaseInitializer:
async def fix_structure(self):
"""
- Clean up parser output directories after image migration.
+ 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...")
- 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.
+ # Find nested content lists
+ content_list_moves = []
+ for doc_dir in self.content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
- This method now only:
- 1. Checks if there are any leftover nested directories to clean up
- 2. Removes empty temporary parser output directories
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
- Supports both 'auto' (MinerU) and 'docling' parser output directories.
- """
- logger.info("\nChecking for leftover 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))
- # Support both 'auto' (MinerU) and 'docling' parser output directories
- parser_subdirs = ["auto", "docling"]
- cleaned_count = 0
+ # 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}")
- # Find and remove empty parser output directories
- for doc_dir in list(self.content_list_dir.glob("*")):
+ # Find and move nested images
+ for doc_dir in self.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:
- # 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
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
- if cleaned_count > 0:
- logger.info(f"βœ“ Cleaned up {cleaned_count} empty parser directories")
- else:
- logger.info("βœ“ No cleanup needed (structure already organized)")
+ 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!")
def extract_numbered_items(self, batch_size: int = 20):
"""
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index 32c04525c..ebba790da 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -413,6 +413,7 @@ class KnowledgeBaseManager:
files.extend(folder.glob(f"**/*{ext}"))
# Generate folder ID
+ import hashlib
folder_id = hashlib.md5( # noqa: S324
str(folder).encode(), usedforsecurity=False
diff --git a/src/logging/__init__.py b/src/logging/__init__.py
index fac531675..1ae905dac 100644
--- a/src/logging/__init__.py
+++ b/src/logging/__init__.py
@@ -39,7 +39,6 @@ from .adapters import (
from .config import (
LoggingConfig,
get_default_log_dir,
- get_global_log_level,
load_logging_config,
)
@@ -59,7 +58,6 @@ from .logger import (
LogLevel,
get_logger,
reset_logger,
- set_default_service_prefix,
)
# Statistics tracking
@@ -77,7 +75,6 @@ __all__ = [
"LogLevel",
"get_logger",
"reset_logger",
- "set_default_service_prefix",
"ConsoleFormatter",
"FileFormatter",
# Handlers
@@ -103,5 +100,4 @@ __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 6e59c2dd3..52adaff41 100644
--- a/src/logging/adapters/lightrag.py
+++ b/src/logging/adapters/lightrag.py
@@ -4,7 +4,6 @@ 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
@@ -32,21 +31,17 @@ class LightRAGLogForwarder(logging.Handler):
def emit(self, record: logging.LogRecord):
"""
- Forward log record to DeepTutor logger with proper level mapping.
+ Forward log record to DeepTutor logger.
+ All logs are forwarded as info level to maintain consistent format.
"""
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()
- # 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)
+ # 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)
except Exception:
# Avoid errors in forwarding from affecting main flow
@@ -55,35 +50,35 @@ class LightRAGLogForwarder(logging.Handler):
def get_lightrag_forwarding_config() -> dict:
"""
- Load LightRAG forwarding configuration from config/main.yaml.
+ Load LightRAG forwarding configuration from 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", {})
- # Use the unified global log level
- level = get_global_log_level()
+ forwarding_config = config.get("logging", {}).get("lightrag_forwarding", {})
return {
- "enabled": True,
- "min_level": level,
- "logger_names": logging_config.get(
- "rag_logger_names", {"knowledge_init": "RAG-Init", "rag_tool": "RAG"}
+ "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"}
),
}
except Exception:
# Return defaults if config loading fails
return {
"enabled": True,
- "min_level": "DEBUG",
- "logger_names": {"knowledge_init": "RAG-Init", "rag_tool": "RAG"},
+ "min_level": "INFO",
+ "add_prefix": True,
+ "logger_names": {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"},
}
diff --git a/src/logging/config.py b/src/logging/config.py
index f41ca2b51..e8d16f09e 100644
--- a/src/logging/config.py
+++ b/src/logging/config.py
@@ -2,36 +2,42 @@
Logging Configuration
=====================
-Unified logging configuration for the entire DeepTutor system.
-A single `level` parameter controls all logging (including RAG modules).
+Configuration settings for the logging system.
"""
from dataclasses import dataclass
from pathlib import Path
-from typing import Dict, Optional
+from typing import 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."""
@@ -39,22 +45,6 @@ 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.
@@ -69,14 +59,22 @@ 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("save_to_file", 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"),
log_dir=get_path_from_config(config, "user_log_dir"),
- rag_logger_names=logging_config.get("rag_logger_names"),
+ 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
+ ),
)
except Exception:
return LoggingConfig()
diff --git a/src/logging/handlers/console.py b/src/logging/handlers/console.py
index 521cb867d..ea4f3d99a 100644
--- a/src/logging/handlers/console.py
+++ b/src/logging/handlers/console.py
@@ -3,15 +3,59 @@
Console Log Handler
===================
-Color-coded console output with standard level tags.
+Color-coded console output with symbols.
"""
import logging
import sys
-from typing import Optional
-# Import ConsoleFormatter from the main logger module to avoid duplication
-from ..logger import ConsoleFormatter
+
+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}"
class ConsoleHandler(logging.StreamHandler):
@@ -19,14 +63,13 @@ class ConsoleHandler(logging.StreamHandler):
Console handler with color-coded output.
"""
- def __init__(self, level: int = logging.INFO, service_prefix: Optional[str] = None):
+ def __init__(self, level: int = logging.INFO):
"""
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(service_prefix=service_prefix))
+ self.setFormatter(ConsoleFormatter())
diff --git a/src/logging/handlers/file.py b/src/logging/handlers/file.py
index c7985d3bc..7ae3dce3a 100644
--- a/src/logging/handlers/file.py
+++ b/src/logging/handlers/file.py
@@ -13,8 +13,24 @@ from logging.handlers import RotatingFileHandler as BaseRotatingFileHandler
from pathlib import Path
from typing import Optional
-# Import FileFormatter from the main logger module to avoid duplication
-from ..logger import FileFormatter
+
+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)
class FileHandler(logging.FileHandler):
@@ -127,7 +143,7 @@ class JSONFileHandler(logging.Handler):
}
# Add extra fields if present
- for key in ["display_level", "tool_name", "elapsed_ms", "tokens"]:
+ for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
if hasattr(record, key):
entry[key] = getattr(record, key)
@@ -164,7 +180,7 @@ def create_task_logger(
log_path.mkdir(parents=True, exist_ok=True)
# Create logger
- logger = logging.getLogger(f"deeptutor.{module_name}.{task_id}")
+ logger = logging.getLogger(f"ai_tutor.{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 754339ad3..92c0c3b35 100644
--- a/src/logging/handlers/websocket.py
+++ b/src/logging/handlers/websocket.py
@@ -8,7 +8,6 @@ Handlers for streaming logs to WebSocket clients.
import asyncio
import logging
-from typing import Optional
class WebSocketLogHandler(logging.Handler):
@@ -26,24 +25,27 @@ class WebSocketLogHandler(logging.Handler):
await websocket.send_json(log_entry)
"""
- def __init__(
- self,
- queue: asyncio.Queue,
- include_module: bool = True,
- service_prefix: Optional[str] = None,
- ):
+ # Symbols for different log types (matching ConsoleFormatter)
+ SYMBOLS = {
+ "DEBUG": "Β·",
+ "INFO": "●",
+ "SUCCESS": "βœ“",
+ "WARNING": "⚠",
+ "ERROR": "βœ—",
+ "CRITICAL": "βœ—",
+ }
+
+ def __init__(self, queue: asyncio.Queue, include_module: bool = True):
"""
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):
@@ -51,31 +53,25 @@ class WebSocketLogHandler(logging.Handler):
try:
msg = self.format(record)
- # Get display level
+ # Get symbol
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 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}"
+ # Build formatted content
+ if self.include_module:
+ content = f"[{module_name}] {symbol} {msg}"
else:
- if self.include_module:
- content = f"{level_tag} [{module_name}] {msg}"
- else:
- content = f"{level_tag} {msg}"
+ content = f"{symbol} {msg}"
# Construct structured message
log_entry = {
"type": "log",
"level": display_level,
"module": module_name,
+ "symbol": symbol,
"content": content,
"message": msg,
"timestamp": record.created,
@@ -97,7 +93,7 @@ class LogInterceptor:
Usage:
queue = asyncio.Queue()
- logger = logging.getLogger("deeptutor.Solver")
+ logger = logging.getLogger("ai_tutor.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 f1b0787f7..78640595c 100644
--- a/src/logging/logger.py
+++ b/src/logging/logger.py
@@ -4,14 +4,13 @@ Core Logger Implementation
==========================
Unified logging with consistent format across all modules.
-Format: [LEVEL] [Module] Message
+Format: [Module] Symbol Message
Example outputs:
- [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
+ [Solver] βœ“ Ready in 2.3s
+ [Research] β†’ Starting deep research...
+ [Guide] β†’ Compiling knowledge points
+ [Knowledge] βœ“ Indexed 150 documents
"""
from datetime import datetime
@@ -22,26 +21,26 @@ from pathlib import Path
import sys
from typing import Any, List, Optional, Union
-from src.config.constants import PROJECT_ROOT
+from src.config.constants import LOG_SYMBOLS, PROJECT_ROOT
class LogLevel(Enum):
- """Log levels with standard tags"""
+ """Log levels with associated symbols"""
- DEBUG = "DEBUG"
- INFO = "INFO"
- SUCCESS = "SUCCESS"
- WARNING = "WARNING"
- ERROR = "ERROR"
- CRITICAL = "CRITICAL"
- PROGRESS = "PROGRESS"
- COMPLETE = "COMPLETE"
+ 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
class ConsoleFormatter(logging.Formatter):
"""
- Clean console formatter with colors and standard level tags.
- Format: [LEVEL] [Module] Message
+ Clean console formatter with colors and symbols.
+ Format: [Module] Symbol Message
"""
# ANSI color codes
@@ -52,46 +51,36 @@ 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"
- def __init__(self, service_prefix: Optional[str] = None):
- """
- Initialize console formatter.
+ # Symbols for different log types
+ SYMBOLS = LOG_SYMBOLS
- Args:
- service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
- """
+ def __init__(self):
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 display level (may be custom like SUCCESS, PROGRESS)
- display_level = getattr(record, "display_level", record.levelname)
-
- # Get module name
+ # Get module name (padded to 12 chars for alignment)
module = getattr(record, "module_name", record.name)
-
- # Build module tag [Module]
- module_tag = f"[{module}]"
-
- # Build level tag with colon
- level_tag = f"{display_level}:"
-
+ module_padded = f"[{module}]".ljust(14)
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))
# Use pre-computed TTY status
- if self.use_colors:
- color = self.COLORS.get(display_level, self.COLORS["INFO"])
+ 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"])
dim = self.DIM
reset = self.RESET
else:
+ # No colors for non-interactive output
color = ""
dim = ""
reset = ""
@@ -99,12 +88,8 @@ class ConsoleFormatter(logging.Formatter):
# Format message
message = record.getMessage()
- # 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}"
+ # Build output: [Module] ● Message
+ return f"{dim}{module_padded}{reset} {color}{symbol}{reset} {message}"
class FileFormatter(logging.Formatter):
@@ -136,7 +121,6 @@ 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")
@@ -152,7 +136,6 @@ class Logger:
console_output: bool = True,
file_output: bool = True,
log_dir: Optional[Union[str, Path]] = None,
- service_prefix: Optional[str] = None,
):
"""
Initialize logger.
@@ -163,17 +146,14 @@ 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"deeptutor.{name}")
+ self.logger = logging.getLogger(f"ai_tutor.{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:
@@ -191,13 +171,13 @@ class Logger:
if console_output:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(self.level)
- console_handler.setFormatter(ConsoleFormatter(service_prefix=service_prefix))
+ console_handler.setFormatter(ConsoleFormatter())
self.logger.addHandler(console_handler)
# File handler
if file_output:
timestamp = datetime.now().strftime("%Y%m%d")
- log_file = log_dir_path / f"deeptutor_{timestamp}.log"
+ log_file = log_dir_path / f"ai_tutor_{timestamp}.log"
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG) # Log everything to file
@@ -254,12 +234,14 @@ 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
@@ -273,43 +255,45 @@ class Logger:
# Standard logging methods
def debug(self, message: str, **kwargs):
- """Debug level log [DEBUG]"""
- self._log(logging.DEBUG, message, **kwargs)
+ """Debug level log (Β·)"""
+ self._log(logging.DEBUG, message, symbol="Β·", **kwargs)
def info(self, message: str, **kwargs):
- """Info level log [INFO]"""
- self._log(logging.INFO, message, **kwargs)
+ """Info level log (●)"""
+ self._log(logging.INFO, message, symbol="●", **kwargs)
def warning(self, message: str, **kwargs):
- """Warning level log [WARNING]"""
- self._log(logging.WARNING, message, **kwargs)
+ """Warning level log (⚠)"""
+ self._log(logging.WARNING, message, symbol="⚠", **kwargs)
def error(self, message: str, **kwargs):
- """Error level log [ERROR]"""
- self._log(logging.ERROR, message, **kwargs)
+ """Error level log (βœ—)"""
+ self._log(logging.ERROR, message, symbol="βœ—", **kwargs)
def critical(self, message: str, **kwargs):
- """Critical level log [CRITICAL]"""
- self._log(logging.CRITICAL, message, **kwargs)
+ """Critical level log (βœ—)"""
+ self._log(logging.CRITICAL, message, symbol="βœ—", **kwargs)
def exception(self, message: str, **kwargs):
"""Log exception with traceback"""
- self.logger.exception(message, extra={"module_name": self.name, "display_level": "ERROR"})
+ self.logger.exception(
+ message, extra={"module_name": self.name, "symbol": "βœ—", "display_level": "ERROR"}
+ )
# Convenience methods
def success(self, message: str, elapsed: Optional[float] = None, **kwargs):
- """Success log [SUCCESS]"""
+ """Success log with checkmark (βœ“)"""
if elapsed is not None:
message = f"{message} in {elapsed:.1f}s"
- self._log(logging.INFO, message, display_level="SUCCESS", **kwargs)
+ self._log(logging.INFO, message, symbol="βœ“", display_level="SUCCESS", **kwargs)
def progress(self, message: str, **kwargs):
- """Progress log [PROGRESS]"""
- self._log(logging.INFO, message, display_level="PROGRESS", **kwargs)
+ """Progress log with arrow (β†’)"""
+ self._log(logging.INFO, message, symbol="β†’", **kwargs)
def complete(self, message: str, **kwargs):
- """Completion log [COMPLETE]"""
- self._log(logging.INFO, message, display_level="COMPLETE", **kwargs)
+ """Completion log with checkmark (βœ“)"""
+ self._log(logging.INFO, message, symbol="βœ“", display_level="SUCCESS", **kwargs)
def stage(self, stage_name: str, status: str = "start", detail: Optional[str] = None):
"""
@@ -320,16 +304,15 @@ class Logger:
status: One of "start", "running", "complete", "skip", "error"
detail: Optional detail message
"""
- # Map status to display level
- status_to_level = {
- "start": "PROGRESS",
- "running": "INFO",
- "complete": "SUCCESS",
- "skip": "INFO",
- "error": "ERROR",
- "warning": "WARNING",
+ symbols = {
+ "start": "β–Ά",
+ "running": "●",
+ "complete": "βœ“",
+ "skip": "β—‹",
+ "error": "βœ—",
+ "warning": "⚠",
}
- display_level = status_to_level.get(status, "INFO")
+ symbol = symbols.get(status, "●")
message = f"{stage_name}"
if status == "complete":
@@ -347,7 +330,10 @@ class Logger:
message += f" | {detail}"
level = logging.ERROR if status == "error" else logging.INFO
- self._log(level, message, display_level=display_level)
+ display_level = (
+ "ERROR" if status == "error" else ("SUCCESS" if status == "complete" else "INFO")
+ )
+ self._log(level, message, symbol=symbol, display_level=display_level)
def tool_call(
self, tool_name: str, status: str = "success", elapsed_ms: Optional[float] = None, **kwargs
@@ -360,6 +346,7 @@ 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")
)
@@ -373,6 +360,7 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
+ symbol=symbol,
display_level=display_level,
)
@@ -406,7 +394,7 @@ class Logger:
parts.append(f"{elapsed:.2f}s")
message = " | ".join(parts)
- self._log(logging.DEBUG, message)
+ self._log(logging.DEBUG, message, symbol="β—†")
def separator(self, char: str = "─", length: int = 50):
"""Print a separator line"""
@@ -432,6 +420,7 @@ 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")
)
@@ -446,6 +435,7 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
+ symbol=symbol,
display_level=display_level,
)
@@ -519,20 +509,22 @@ 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)
- self._log(log_level, "--- Input ---")
+ self._log(log_level, header, symbol="β—†")
+ self._log(
+ log_level, "β”Œβ”€ Input ──────────────────────────────────────────────", symbol=" "
+ )
self._log(
log_level,
(
@@ -540,6 +532,7 @@ class Logger:
if len(system_prompt) > 200
else f"System: {system_prompt}"
),
+ symbol=" ",
)
self._log(
log_level,
@@ -548,9 +541,20 @@ 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 = []
@@ -564,17 +568,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)}")
+ self._log(log_level, f"[Tokens: {' '.join(token_info_parts)}]", symbol=" ")
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)
+ self._log(log_level, message, symbol="β—†")
def update_token_stats(self, summary: dict[str, Any]):
"""Update token statistics (for display manager compatibility)"""
@@ -605,99 +609,67 @@ class Logger:
self.logger.removeHandler(handler)
-# 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
+# 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"] = {}
def get_logger(
name: str = "Main",
- level: Optional[str] = None,
+ level: str = "INFO",
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 (if None, uses global level from config/main.yaml)
+ level: Log level
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, _default_service_prefix
-
- # Use default service prefix if not explicitly provided
- effective_service_prefix = (
- service_prefix if service_prefix is not None else _default_service_prefix
- )
+ global _loggers
- # Load config for log_dir and level
- effective_level = level
- if log_dir is None or effective_level is None:
+ # If log_dir not provided, try to load from config
+ if log_dir is None:
try:
from src.services.config import get_path_from_config, load_config_with_main
- 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()
+ # 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)
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
- cache_key = (name, effective_level, console_output, file_output, log_dir_key, effective_service_prefix)
+ # Create a cache key that includes configuration, using a normalized log_dir
+ cache_key = (name, level, console_output, file_output, log_dir_key)
if cache_key not in _loggers:
_loggers[cache_key] = Logger(
name=name,
- level=effective_level,
+ level=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 a5552b8b6..8070240e1 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 via the unified logging system.
+Outputs summary to terminal at the end of processing.
Usage:
from src.logging import LLMStats
- stats = LLMStats("Solver")
+ stats = LLMStats()
# After each LLM call:
stats.add_call(
@@ -19,15 +19,12 @@ Usage:
)
# At the end:
- stats.log_summary() # Uses logging system
+ stats.print_summary()
"""
from dataclasses import dataclass, field
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Optional
-
-if TYPE_CHECKING:
- from ..logger import Logger
+from typing import Any, Optional
# Model pricing per 1K tokens (USD)
MODEL_PRICING = {
@@ -153,42 +150,25 @@ class LLMStats:
"cost_usd": self.total_cost,
}
- 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.
- """
+ def print_summary(self):
+ """Print summary to terminal."""
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
- 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()
+ 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(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()
+ print(f" Cost : ${self.total_cost:.6f} USD")
+ print("=" * 60)
+ print()
def reset(self):
"""Reset all statistics."""
diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.py
index 44e2f23cb..f33f23972 100644
--- a/src/services/config/unified_config.py
+++ b/src/services/config/unified_config.py
@@ -537,52 +537,7 @@ class UnifiedConfigManager:
return False
data["active_id"] = config_id
- 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}")
+ return self._save_configs(config_type, data)
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 941dd1541..f2105600f 100644
--- a/src/services/llm/client.py
+++ b/src/services/llm/client.py
@@ -31,38 +31,9 @@ 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,
@@ -157,7 +128,6 @@ 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(
@@ -226,7 +196,6 @@ 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 c11ba6650..e071cc6a7 100644
--- a/src/services/llm/config.py
+++ b/src/services/llm/config.py
@@ -26,37 +26,6 @@ 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 9c56bc5dc..fc8467eaa 100644
--- a/src/services/rag/components/indexers/graph.py
+++ b/src/services/rag/components/indexers/graph.py
@@ -51,18 +51,58 @@ 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()
- # 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 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
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 2a87a505e..63da12298 100644
--- a/src/services/rag/components/indexers/lightrag.py
+++ b/src/services/rag/components/indexers/lightrag.py
@@ -53,17 +53,57 @@ 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()
- # 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 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
# 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 8c1e3137f..a594cb32b 100644
--- a/src/services/rag/components/retrievers/hybrid.py
+++ b/src/services/rag/components/retrievers/hybrid.py
@@ -50,18 +50,58 @@ 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()
- # 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 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
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 334f24861..c945a3617 100644
--- a/src/services/rag/components/retrievers/lightrag.py
+++ b/src/services/rag/components/retrievers/lightrag.py
@@ -52,17 +52,57 @@ 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()
- # 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 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
# Create pure LightRAG instance (no multimodal)
rag = LightRAG(
diff --git a/src/services/rag/factory.py b/src/services/rag/factory.py
index 0516bf952..fdf13de91 100644
--- a/src/services/rag/factory.py
+++ b/src/services/rag/factory.py
@@ -9,12 +9,10 @@ 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)
}
@@ -43,12 +41,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, raganything_docling: classes that need instantiation
+ # - llamaindex, raganything: 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", "raganything_docling"):
- # LlamaIndexPipeline, RAGAnythingPipeline, and RAGAnythingDoclingPipeline are classes
+ elif name in ("llamaindex", "raganything"):
+ # LlamaIndexPipeline and RAGAnythingPipeline are classes
if kb_base_dir:
kwargs["kb_base_dir"] = kb_base_dir
return factory(**kwargs)
@@ -77,13 +75,8 @@ def list_pipelines() -> List[Dict[str, str]]:
},
{
"id": "raganything",
- "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.",
+ "name": "RAG-Anything",
+ "description": "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
},
]
diff --git a/src/services/rag/pipelines/__init__.py b/src/services/rag/pipelines/__init__.py
index 7274f4492..20c7f3297 100644
--- a/src/services/rag/pipelines/__init__.py
+++ b/src/services/rag/pipelines/__init__.py
@@ -9,11 +9,9 @@ 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 38dd2363c..c072d8884 100644
--- a/src/services/rag/pipelines/raganything.py
+++ b/src/services/rag/pipelines/raganything.py
@@ -9,13 +9,11 @@ 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:
"""
@@ -73,19 +71,106 @@ 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()
- # 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()
+ # 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)
config = RAGAnythingConfig(
working_dir=working_dir,
@@ -112,15 +197,7 @@ class RAGAnythingPipeline:
**kwargs,
) -> bool:
"""
- 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.
+ Initialize KB using RAG-Anything's process_document_complete().
Uses FileTypeRouter to classify files and route them appropriately:
- PDF files -> MinerU parser (full document analysis)
@@ -135,21 +212,13 @@ 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)
@@ -166,47 +235,19 @@ 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
- 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(
+ self.logger.info(
+ f"Processing [{idx}/{total_files}] (MinerU): {Path(file_path).name}"
+ )
+ await rag.process_document_complete(
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
@@ -222,17 +263,10 @@ 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 ({total_images_migrated} images migrated)"
- )
+ self.logger.info(f"KB '{kb_name}' initialized successfully")
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
deleted file mode 100644
index 306534d5f..000000000
--- a/src/services/rag/pipelines/raganything_docling.py
+++ /dev/null
@@ -1,368 +0,0 @@
-"""
-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
deleted file mode 100644
index 694b99d5c..000000000
--- a/src/services/rag/utils/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""
-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
deleted file mode 100644
index 2785aa207..000000000
--- a/src/services/rag/utils/image_migration.py
+++ /dev/null
@@ -1,296 +0,0 @@
-"""
-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/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.py
index 0f2212dbf..9f617f459 100644
--- a/tests/services/rag/test_pipeline_integration.py
+++ b/tests/services/rag/test_pipeline_integration.py
@@ -9,10 +9,10 @@ Tests the full workflow: initialize -> search -> delete
Usage:
# Test specific pipeline
python tests/services/rag/test_pipeline_integration.py --pipeline llamaindex
-
+
# Test all pipelines
python tests/services/rag/test_pipeline_integration.py --pipeline all
-
+
# Using pytest
pytest tests/services/rag/test_pipeline_integration.py -v --pipeline llamaindex
"""
@@ -20,17 +20,16 @@ Usage:
import argparse
import asyncio
import os
-from pathlib import Path
import shutil
import sys
import tempfile
+from pathlib import Path
# Add project root to path
project_root = Path(__file__).resolve().parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
-
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
@@ -41,7 +40,6 @@ TEST_FILE = project_root / "tests" / "services" / "rag" / "testfile.txt"
class Colors:
"""Terminal colors"""
-
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
@@ -75,57 +73,59 @@ def print_info(text: str):
class PipelineIntegrationTest:
"""
Integration test for a specific RAG pipeline.
-
+
Tests:
1. Knowledge base initialization with test file
2. Search/retrieval
3. Knowledge base deletion
"""
-
+
def __init__(self, pipeline_name: str, test_file: Path = TEST_FILE):
self.pipeline_name = pipeline_name
self.test_file = test_file
self.temp_dir = None
self.kb_name = f"test_kb_{pipeline_name}"
self.service = None
-
+
async def setup(self):
"""Setup test environment"""
# Create temporary directory
self.temp_dir = tempfile.mkdtemp(prefix=f"rag_test_{self.pipeline_name}_")
print_info(f"Created temp directory: {self.temp_dir}")
-
+
# Initialize service with temp directory
from src.services.rag import RAGService
-
- self.service = RAGService(kb_base_dir=self.temp_dir, provider=self.pipeline_name)
-
+ self.service = RAGService(
+ kb_base_dir=self.temp_dir,
+ provider=self.pipeline_name
+ )
+
# Verify test file exists
if not self.test_file.exists():
raise FileNotFoundError(f"Test file not found: {self.test_file}")
-
+
print_info(f"Test file: {self.test_file}")
print_info(f"Provider: {self.pipeline_name}")
-
+
async def teardown(self):
"""Cleanup test environment"""
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
print_info(f"Cleaned up temp directory: {self.temp_dir}")
-
+
async def test_initialize(self) -> bool:
"""Test knowledge base initialization"""
print("\n πŸ“š Testing initialization...")
-
+
try:
success = await self.service.initialize(
kb_name=self.kb_name,
file_paths=[str(self.test_file)],
)
-
+
if success:
print_success("Knowledge base initialized successfully")
-
+
# Verify KB directory was created
kb_dir = Path(self.temp_dir) / self.kb_name
if kb_dir.exists():
@@ -135,23 +135,22 @@ class PipelineIntegrationTest:
print_info(f"KB contains {len(contents)} files/directories")
else:
print_warning("KB directory not found after initialization")
-
+
return True
else:
print_error("Initialization returned False")
return False
-
+
except Exception as e:
print_error(f"Initialization failed: {e}")
import traceback
-
traceback.print_exc()
return False
-
+
async def test_search(self) -> bool:
"""Test search/retrieval"""
print("\n πŸ” Testing search...")
-
+
# Test query based on test file content
# testfile.txt contains: "Shandong province has a pancake."
test_queries = [
@@ -159,31 +158,31 @@ class PipelineIntegrationTest:
("pancake", "Search for 'pancake'"),
("What does Shandong have?", "Natural question"),
]
-
+
all_passed = True
-
+
for query, description in test_queries:
try:
print_info(f"Query: {query} ({description})")
-
+
result = await self.service.search(
query=query,
kb_name=self.kb_name,
mode="naive" if self.pipeline_name in ["llamaindex"] else "hybrid",
)
-
+
# Check result structure
if not isinstance(result, dict):
print_error(f"Result is not a dict: {type(result)}")
all_passed = False
continue
-
+
# Check required fields
required_fields = ["query", "answer", "content", "provider"]
missing = [f for f in required_fields if f not in result]
if missing:
print_warning(f"Missing fields: {missing}")
-
+
# Check content
answer = result.get("answer", "")
if answer:
@@ -193,23 +192,22 @@ class PipelineIntegrationTest:
print_info(f"Preview: {preview}")
else:
print_warning("Empty answer")
-
+
except Exception as e:
print_error(f"Search failed: {e}")
import traceback
-
traceback.print_exc()
all_passed = False
-
+
return all_passed
-
+
async def test_search_via_rag_tool(self) -> bool:
"""Test search via rag_tool.py (the actual interface used by agents)"""
print("\n πŸ”§ Testing via rag_tool.py...")
-
+
try:
from src.tools.rag_tool import rag_search
-
+
result = await rag_search(
query="What does Shandong have?",
kb_name=self.kb_name,
@@ -217,53 +215,52 @@ class PipelineIntegrationTest:
kb_base_dir=self.temp_dir,
mode="naive",
)
-
+
if result and result.get("answer"):
- print_success("rag_tool.py search successful")
+ print_success(f"rag_tool.py search successful")
print_info(f"Provider: {result.get('provider')}")
print_info(f"Answer preview: {result['answer'][:100]}...")
return True
else:
print_warning("rag_tool.py returned empty result")
return False
-
+
except Exception as e:
print_error(f"rag_tool.py search failed: {e}")
import traceback
-
traceback.print_exc()
return False
-
+
async def test_delete(self) -> bool:
"""Test knowledge base deletion"""
print("\n πŸ—‘οΈ Testing deletion...")
-
+
try:
success = await self.service.delete(kb_name=self.kb_name)
-
+
if success:
print_success("Knowledge base deleted successfully")
-
+
# Verify KB directory was removed
kb_dir = Path(self.temp_dir) / self.kb_name
if not kb_dir.exists():
print_success("KB directory removed")
else:
print_warning("KB directory still exists after deletion")
-
+
return True
else:
print_warning("Deletion returned False (KB may not exist)")
return True # Not necessarily a failure
-
+
except Exception as e:
print_error(f"Deletion failed: {e}")
return False
-
+
async def run_all_tests(self) -> dict:
"""Run all tests for this pipeline"""
print_header(f"Testing Pipeline: {self.pipeline_name}")
-
+
results = {
"pipeline": self.pipeline_name,
"setup": False,
@@ -273,27 +270,26 @@ class PipelineIntegrationTest:
"delete": False,
"cleanup": False,
}
-
+
try:
# Setup
await self.setup()
results["setup"] = True
-
+
# Initialize
results["initialize"] = await self.test_initialize()
-
+
# Search (only if initialize succeeded)
if results["initialize"]:
results["search"] = await self.test_search()
results["rag_tool"] = await self.test_search_via_rag_tool()
-
+
# Delete
results["delete"] = await self.test_delete()
-
+
except Exception as e:
print_error(f"Test failed with exception: {e}")
import traceback
-
traceback.print_exc()
finally:
# Cleanup
@@ -302,14 +298,13 @@ class PipelineIntegrationTest:
results["cleanup"] = True
except Exception as e:
print_error(f"Cleanup failed: {e}")
-
+
return results
def get_available_pipelines():
"""Get list of available pipelines"""
from src.services.rag import RAGService
-
return [p["id"] for p in RAGService.list_providers()]
@@ -323,43 +318,43 @@ async def run_all_pipeline_tests() -> list:
"""Run tests for all pipelines"""
pipelines = get_available_pipelines()
results = []
-
+
for pipeline in pipelines:
result = await run_pipeline_test(pipeline)
results.append(result)
-
+
return results
def print_summary(results: list):
"""Print test summary"""
print_header("Test Summary")
-
+
all_passed = True
-
+
for result in results:
pipeline = result["pipeline"]
tests = ["setup", "initialize", "search", "rag_tool", "delete", "cleanup"]
passed = sum(1 for t in tests if result.get(t, False))
total = len(tests)
-
+
if passed == total:
print_success(f"{pipeline}: {passed}/{total} tests passed")
else:
print_error(f"{pipeline}: {passed}/{total} tests passed")
all_passed = False
-
+
# Show failed tests
for test in tests:
if not result.get(test, False):
print_error(f" - {test} failed")
-
+
print()
if all_passed:
print(f"{Colors.GREEN}{Colors.BOLD}All tests passed!{Colors.END}")
else:
print(f"{Colors.RED}{Colors.BOLD}Some tests failed.{Colors.END}")
-
+
return all_passed
@@ -367,23 +362,26 @@ async def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="RAG Pipeline Integration Tests")
parser.add_argument(
- "--pipeline",
- "-p",
+ "--pipeline", "-p",
type=str,
default="llamaindex",
- help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex",
+ help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex"
)
- parser.add_argument("--list", "-l", action="store_true", help="List available pipelines")
-
+ parser.add_argument(
+ "--list", "-l",
+ action="store_true",
+ help="List available pipelines"
+ )
+
args = parser.parse_args()
-
+
# List pipelines
if args.list:
print_header("Available Pipelines")
for pipeline in get_available_pipelines():
print_info(pipeline)
return
-
+
# Run tests
if args.pipeline.lower() == "all":
results = await run_all_pipeline_tests()
@@ -394,9 +392,9 @@ async def main():
print_error(f"Unknown pipeline: {args.pipeline}")
print_info(f"Available: {available}")
sys.exit(1)
-
+
results = [await run_pipeline_test(args.pipeline)]
-
+
# Print summary
success = print_summary(results)
sys.exit(0 if success else 1)
@@ -405,23 +403,28 @@ async def main():
# Pytest support
def pytest_addoption(parser):
"""Add pytest command line options"""
- parser.addoption("--pipeline", action="store", default="llamaindex", help="Pipeline to test")
+ parser.addoption(
+ "--pipeline",
+ action="store",
+ default="llamaindex",
+ help="Pipeline to test"
+ )
class TestPipelineIntegration:
"""Pytest test class"""
-
+
@staticmethod
def test_pipeline(request):
"""Test the specified pipeline"""
pipeline_name = request.config.getoption("--pipeline")
-
+
async def _run():
if pipeline_name.lower() == "all":
results = await run_all_pipeline_tests()
else:
results = [await run_pipeline_test(pipeline_name)]
-
+
# Assert all tests passed
for result in results:
assert result["setup"], f"{result['pipeline']}: Setup failed"
@@ -429,12 +432,12 @@ class TestPipelineIntegration:
assert result["search"], f"{result['pipeline']}: Search failed"
assert result["rag_tool"], f"{result['pipeline']}: rag_tool test failed"
assert result["delete"], f"{result['pipeline']}: Delete failed"
-
+
asyncio.run(_run())
if __name__ == "__main__":
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-
+
asyncio.run(main())
diff --git a/tests/services/rag/test_rag_pipelines.py b/tests/services/rag/test_rag_pipelines.py
index a20ac1fbc..bef019720 100644
--- a/tests/services/rag/test_rag_pipelines.py
+++ b/tests/services/rag/test_rag_pipelines.py
@@ -10,16 +10,19 @@ RAG Pipeline Integration Tests
θΏθ‘Œζ–ΉεΌοΌš
python -m pytest tests/services/rag/test_rag_pipelines.py -v
-
+
ζˆ–η›΄ζŽ₯运葌:
python tests/services/rag/test_rag_pipelines.py
"""
+import asyncio
+import json
import os
-from pathlib import Path
import shutil
import sys
import tempfile
+from pathlib import Path
+from typing import Dict, List, Optional
import unittest
# Add project root to path
@@ -27,25 +30,24 @@ project_root = Path(__file__).resolve().parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
-
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
class RAGPipelineTestBase:
"""Base class for RAG pipeline tests"""
-
+
TEST_KB_NAME = "test_rag_pipeline"
TEST_QUERY = "What is machine learning?"
-
+
@classmethod
def create_test_document(cls, temp_dir: str) -> str:
"""Create a test document for testing"""
test_content = """
# Introduction to Machine Learning
-Machine learning is a subset of artificial intelligence (AI) that provides systems
-the ability to automatically learn and improve from experience without being explicitly
+Machine learning is a subset of artificial intelligence (AI) that provides systems
+the ability to automatically learn and improve from experience without being explicitly
programmed.
## Types of Machine Learning
@@ -58,7 +60,7 @@ Examples:
- Classification: Predicting discrete labels
- Regression: Predicting continuous values
-### Unsupervised Learning
+### Unsupervised Learning
Unsupervised learning is a type of machine learning where the model is trained on unlabeled data.
The model learns to find patterns and structures in the data.
@@ -92,185 +94,185 @@ Machine learning has many applications in various fields including:
- Recommendation systems
- Autonomous vehicles
"""
-
+
# Create both .md and .txt versions
md_path = os.path.join(temp_dir, "ml_intro.md")
with open(md_path, "w", encoding="utf-8") as f:
f.write(test_content)
-
+
return md_path
class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):
"""Test rag_tool.py interface with all pipelines"""
-
+
async def test_list_available_providers(self):
"""Test listing available RAG providers"""
- from src.tools.rag_tool import get_available_providers
-
+ from src.tools.rag_tool import get_available_providers, list_pipelines
+
providers = get_available_providers()
print("\n=== Available RAG Providers ===")
for p in providers:
print(f" - {p['id']}: {p['name']} - {p['description']}")
-
+
self.assertIsInstance(providers, list)
self.assertGreater(len(providers), 0)
-
+
# Check expected providers
provider_ids = [p["id"] for p in providers]
expected = ["raganything", "lightrag", "llamaindex", "academic"]
for expected_id in expected:
self.assertIn(expected_id, provider_ids, f"Missing provider: {expected_id}")
-
+
async def test_get_current_provider(self):
"""Test getting current RAG provider"""
from src.tools.rag_tool import get_current_provider
-
+
provider = get_current_provider()
print(f"\n=== Current Provider: {provider} ===")
-
+
self.assertIsInstance(provider, str)
self.assertIn(provider, ["raganything", "lightrag", "llamaindex", "academic"])
-
+
async def test_has_pipeline_valid(self):
"""Test has_pipeline with valid pipeline names"""
from src.services.rag.factory import has_pipeline
-
+
for name in ["raganything", "lightrag", "llamaindex", "academic"]:
self.assertTrue(has_pipeline(name), f"Pipeline {name} should exist")
-
+
async def test_has_pipeline_invalid(self):
"""Test has_pipeline with invalid pipeline name"""
from src.services.rag.factory import has_pipeline
-
+
self.assertFalse(has_pipeline("nonexistent"))
self.assertFalse(has_pipeline(""))
class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):
"""Test pipeline factory functionality"""
-
+
async def test_get_pipeline_raganything(self):
"""Test getting RAGAnything pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
-
+
pipeline = get_pipeline("raganything")
self.assertIsInstance(pipeline, RAGAnythingPipeline)
print(f"\nβœ“ RAGAnything pipeline created: {type(pipeline).__name__}")
-
+
async def test_get_pipeline_lightrag(self):
"""Test getting LightRAG pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("lightrag")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "lightrag")
print(f"\nβœ“ LightRAG pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_llamaindex(self):
"""Test getting LlamaIndex pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("llamaindex")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "llamaindex")
print(f"\nβœ“ LlamaIndex pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_academic(self):
"""Test getting Academic pipeline"""
from src.services.rag.factory import get_pipeline
from src.services.rag.pipeline import RAGPipeline
-
+
pipeline = get_pipeline("academic")
self.assertIsInstance(pipeline, RAGPipeline)
self.assertEqual(pipeline.name, "academic")
print(f"\nβœ“ Academic pipeline created: {pipeline.name}")
-
+
async def test_get_pipeline_invalid(self):
"""Test getting invalid pipeline raises error"""
from src.services.rag.factory import get_pipeline
-
+
with self.assertRaises(ValueError) as context:
get_pipeline("nonexistent")
-
+
self.assertIn("Unknown pipeline", str(context.exception))
- print("\nβœ“ Invalid pipeline correctly raises error")
+ print(f"\nβœ“ Invalid pipeline correctly raises error")
class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test RAGAnything pipeline (requires RAG-Anything library)"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_raganything_availability(self):
"""Test if RAGAnything dependencies are available"""
print("\n=== Testing RAGAnything Availability ===")
-
+
try:
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
-
pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)
print("βœ“ RAGAnythingPipeline class available")
-
+
# Check RAG-Anything import
try:
pipeline._setup_raganything_path()
from raganything import RAGAnything, RAGAnythingConfig
-
print("βœ“ RAG-Anything library available")
return True
except ImportError as e:
print(f"⚠ RAG-Anything library not available: {e}")
print(" Install RAG-Anything to enable full functionality")
return False
-
+
except ImportError as e:
print(f"βœ— Failed to import RAGAnythingPipeline: {e}")
return False
-
+
@unittest.skipUnless(
os.environ.get("TEST_RAG_ANYTHING", "").lower() == "true",
- "Set TEST_RAG_ANYTHING=true to run RAGAnything tests",
+ "Set TEST_RAG_ANYTHING=true to run RAGAnything tests"
)
async def test_raganything_full_workflow(self):
"""Test RAGAnything full workflow: initialize -> search -> delete"""
print("\n=== Testing RAGAnything Full Workflow ===")
-
+
from src.services.rag.pipelines.raganything import RAGAnythingPipeline
-
+
pipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)
-
+
# Test initialization
print(f"Initializing KB with document: {self.test_doc}")
success = await pipeline.initialize(
kb_name=self.TEST_KB_NAME,
file_paths=[self.test_doc],
- extract_numbered_items=False, # Skip for speed
+ extract_numbered_items=False # Skip for speed
)
self.assertTrue(success)
print("βœ“ Knowledge base initialized")
-
+
# Test search
print(f"Searching: {self.TEST_QUERY}")
result = await pipeline.search(
- query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME, mode="naive"
+ query=self.TEST_QUERY,
+ kb_name=self.TEST_KB_NAME,
+ mode="naive"
)
self.assertIn("answer", result)
self.assertIn("content", result)
print(f"βœ“ Search result: {result['answer'][:100]}...")
-
+
# Test delete
deleted = await pipeline.delete(kb_name=self.TEST_KB_NAME)
self.assertTrue(deleted)
@@ -279,267 +281,275 @@ class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestB
class TestLlamaIndexPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test LlamaIndex pipeline (lightweight implementation)"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_llamaindex_components(self):
"""Test LlamaIndex pipeline components are properly configured"""
print("\n=== Testing LlamaIndex Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("llamaindex")
-
+
# Check components
self.assertIsNotNone(pipeline._parser)
self.assertGreater(len(pipeline._chunkers), 0)
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"βœ“ Parser: {pipeline._parser.name}")
print(f"βœ“ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"βœ“ Embedder: {pipeline._embedder.name}")
print(f"βœ“ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"βœ“ Retriever: {pipeline._retriever.name}")
-
+
@unittest.skipUnless(
- os.environ.get("TEST_LLAMAINDEX", "").lower() == "true"
- or os.environ.get("TEST_ALL_PIPELINES", "").lower() == "true",
- "Set TEST_LLAMAINDEX=true to run LlamaIndex tests",
+ os.environ.get("TEST_LLAMAINDEX", "").lower() == "true" or
+ os.environ.get("TEST_ALL_PIPELINES", "").lower() == "true",
+ "Set TEST_LLAMAINDEX=true to run LlamaIndex tests"
)
async def test_llamaindex_full_workflow(self):
"""Test LlamaIndex pipeline full workflow"""
print("\n=== Testing LlamaIndex Full Workflow ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("llamaindex")
-
+
# Patch the kb_base_dir for indexer and retriever
for indexer in pipeline._indexers:
indexer.kb_base_dir = self.test_kb_dir
pipeline._retriever.kb_base_dir = self.test_kb_dir
-
+
# Test initialization
print(f"Initializing KB with document: {self.test_doc}")
try:
success = await pipeline.initialize(
- kb_name=self.TEST_KB_NAME, file_paths=[self.test_doc]
+ kb_name=self.TEST_KB_NAME,
+ file_paths=[self.test_doc]
)
self.assertTrue(success)
print("βœ“ Knowledge base initialized")
except Exception as e:
print(f"⚠ Initialization failed (may need PDF support): {e}")
return
-
+
# Test search
print(f"Searching: {self.TEST_QUERY}")
- result = await pipeline.search(query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME)
+ result = await pipeline.search(
+ query=self.TEST_QUERY,
+ kb_name=self.TEST_KB_NAME
+ )
self.assertIn("answer", result)
print(f"βœ“ Search result: {result.get('answer', '')[:100]}...")
class TestLightRAGPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test LightRAG pipeline (requires RAG-Anything)"""
-
+
async def test_lightrag_components(self):
"""Test LightRAG pipeline components are properly configured"""
print("\n=== Testing LightRAG Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("lightrag")
-
+
# Check components
self.assertIsNotNone(pipeline._parser)
self.assertGreater(len(pipeline._chunkers), 0)
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"βœ“ Parser: {pipeline._parser.name}")
print(f"βœ“ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"βœ“ Embedder: {pipeline._embedder.name}")
print(f"βœ“ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"βœ“ Retriever: {pipeline._retriever.name}")
-
+
# Note: This pipeline requires RAG-Anything for full functionality
print("\n⚠ Note: LightRAG pipeline requires RAG-Anything for search/indexing")
class TestAcademicPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test Academic pipeline (requires RAG-Anything)"""
-
+
async def test_academic_components(self):
"""Test Academic pipeline components are properly configured"""
print("\n=== Testing Academic Pipeline Components ===")
-
+
from src.services.rag.factory import get_pipeline
-
+
pipeline = get_pipeline("academic")
-
+
# Check components - Academic has 2 chunkers
self.assertIsNotNone(pipeline._parser)
self.assertEqual(len(pipeline._chunkers), 2) # SemanticChunker + NumberedItemExtractor
self.assertIsNotNone(pipeline._embedder)
self.assertGreater(len(pipeline._indexers), 0)
self.assertIsNotNone(pipeline._retriever)
-
+
print(f"βœ“ Parser: {pipeline._parser.name}")
print(f"βœ“ Chunkers: {[c.name for c in pipeline._chunkers]}")
print(f"βœ“ Embedder: {pipeline._embedder.name}")
print(f"βœ“ Indexers: {[i.name for i in pipeline._indexers]}")
print(f"βœ“ Retriever: {pipeline._retriever.name}")
-
+
# Note: This pipeline requires RAG-Anything for full functionality
print("\n⚠ Note: Academic pipeline requires RAG-Anything for search/indexing")
class TestRAGToolWithProviders(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase):
"""Test rag_tool.py with different providers"""
-
+
def setUp(self):
"""Set up test fixtures"""
self.temp_dir = tempfile.mkdtemp()
self.test_doc = self.create_test_document(self.temp_dir)
self.test_kb_dir = os.path.join(self.temp_dir, "knowledge_bases")
os.makedirs(self.test_kb_dir, exist_ok=True)
-
+
def tearDown(self):
"""Clean up test fixtures"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
-
+
async def test_rag_search_invalid_provider(self):
"""Test rag_search with invalid provider raises error"""
from src.tools.rag_tool import rag_search
-
+
print("\n=== Testing Invalid Provider Error ===")
-
+
with self.assertRaises(ValueError) as context:
await rag_search(
- query=self.TEST_QUERY, kb_name=self.TEST_KB_NAME, provider="nonexistent"
+ query=self.TEST_QUERY,
+ kb_name=self.TEST_KB_NAME,
+ provider="nonexistent"
)
-
+
self.assertIn("not found", str(context.exception))
print(f"βœ“ Invalid provider correctly raises error: {context.exception}")
-
+
async def test_rag_search_default_provider(self):
"""Test rag_search uses default provider from env"""
- from src.tools.rag_tool import DEFAULT_RAG_PROVIDER, get_current_provider
-
+ from src.tools.rag_tool import get_current_provider, DEFAULT_RAG_PROVIDER
+
print("\n=== Testing Default Provider ===")
-
+
current = get_current_provider()
print(f"βœ“ Default provider from env: {DEFAULT_RAG_PROVIDER}")
print(f"βœ“ Current provider: {current}")
-
+
# They should match
self.assertEqual(current, os.getenv("RAG_PROVIDER", "raganything"))
class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):
"""Test individual component availability"""
-
+
async def test_parsers_available(self):
"""Test all parsers can be imported"""
print("\n=== Testing Parser Availability ===")
-
- from src.services.rag.components.parsers import MarkdownParser, PDFParser
-
+
+ from src.services.rag.components.parsers import PDFParser, MarkdownParser
+
pdf_parser = PDFParser()
print(f"βœ“ PDFParser: {pdf_parser.name}")
-
+
md_parser = MarkdownParser()
print(f"βœ“ MarkdownParser: {md_parser.name}")
-
+
async def test_chunkers_available(self):
"""Test all chunkers can be imported"""
print("\n=== Testing Chunker Availability ===")
-
+
from src.services.rag.components.chunkers import (
- FixedSizeChunker,
- NumberedItemExtractor,
- SemanticChunker,
+ SemanticChunker, FixedSizeChunker, NumberedItemExtractor
)
-
+
semantic = SemanticChunker()
print(f"βœ“ SemanticChunker: {semantic.name}")
-
+
fixed = FixedSizeChunker()
print(f"βœ“ FixedSizeChunker: {fixed.name}")
-
+
numbered = NumberedItemExtractor()
print(f"βœ“ NumberedItemExtractor: {numbered.name}")
-
+
async def test_embedders_available(self):
"""Test all embedders can be imported"""
print("\n=== Testing Embedder Availability ===")
-
+
from src.services.rag.components.embedders import OpenAIEmbedder
-
+
embedder = OpenAIEmbedder()
print(f"βœ“ OpenAIEmbedder: {embedder.name}")
-
+
async def test_indexers_available(self):
"""Test all indexers can be imported"""
print("\n=== Testing Indexer Availability ===")
-
- from src.services.rag.components.indexers import GraphIndexer, VectorIndexer
-
+
+ from src.services.rag.components.indexers import VectorIndexer, GraphIndexer
+
vector = VectorIndexer()
print(f"βœ“ VectorIndexer: {vector.name}")
-
+
graph = GraphIndexer()
print(f"βœ“ GraphIndexer: {graph.name}")
-
+
async def test_retrievers_available(self):
"""Test all retrievers can be imported"""
print("\n=== Testing Retriever Availability ===")
-
+
from src.services.rag.components.retrievers import DenseRetriever, HybridRetriever
-
+
dense = DenseRetriever()
print(f"βœ“ DenseRetriever: {dense.name}")
-
+
hybrid = HybridRetriever()
print(f"βœ“ HybridRetriever: {hybrid.name}")
class TestExistingKnowledgeBase(unittest.IsolatedAsyncioTestCase):
"""Test search on existing knowledge bases"""
-
+
@unittest.skipUnless(
os.environ.get("TEST_EXISTING_KB", "").lower() == "true",
- "Set TEST_EXISTING_KB=true to test existing KBs",
+ "Set TEST_EXISTING_KB=true to test existing KBs"
)
async def test_search_existing_kb(self):
"""Test search on an existing knowledge base"""
print("\n=== Testing Existing Knowledge Base ===")
-
+
from src.tools.rag_tool import rag_search
-
+
# Use default or specified KB
kb_name = os.environ.get("TEST_KB_NAME", "ai-textbook")
query = os.environ.get("TEST_QUERY", "What is machine learning?")
-
+
print(f"KB: {kb_name}")
print(f"Query: {query}")
-
+
# Test with different modes
for mode in ["naive", "hybrid"]:
print(f"\n--- Mode: {mode} ---")
try:
- result = await rag_search(query=query, kb_name=kb_name, mode=mode)
+ result = await rag_search(
+ query=query,
+ kb_name=kb_name,
+ mode=mode
+ )
print(f"βœ“ Provider: {result.get('provider', 'unknown')}")
print(f"βœ“ Answer length: {len(result.get('answer', ''))} chars")
print(f"βœ“ Preview: {result.get('answer', '')[:200]}...")
@@ -552,19 +562,19 @@ def run_quick_tests():
print("=" * 60)
print("Running Quick RAG Pipeline Tests")
print("=" * 60)
-
+
# Run only fast tests
loader = unittest.TestLoader()
suite = unittest.TestSuite()
-
+
# Add quick tests
suite.addTests(loader.loadTestsFromTestCase(TestRAGToolIntegration))
suite.addTests(loader.loadTestsFromTestCase(TestPipelineFactory))
suite.addTests(loader.loadTestsFromTestCase(TestComponentAvailability))
-
+
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
-
+
return result.wasSuccessful()
@@ -581,18 +591,18 @@ def run_all_tests():
print(" TEST_KB_NAME=<name> - KB name for existing KB test")
print(" TEST_QUERY=<query> - Query for existing KB test")
print("=" * 60 + "\n")
-
+
unittest.main(verbosity=2)
if __name__ == "__main__":
import argparse
-
+
parser = argparse.ArgumentParser(description="RAG Pipeline Tests")
parser.add_argument("--quick", action="store_true", help="Run only quick tests")
parser.add_argument("--all", action="store_true", help="Run all tests")
args = parser.parse_args()
-
+
if args.quick:
success = run_quick_tests()
sys.exit(0 if success else 1)
diff --git a/tests/services/rag/testfile.txt b/tests/services/rag/testfile.txt
index d8b190987..774a88dff 100644
--- a/tests/services/rag/testfile.txt
+++ b/tests/services/rag/testfile.txt
@@ -1,2 +1,2 @@
this is a test file
-Shandong province has a pancake.
+Shandong province has a pancake.
\ No newline at end of file
diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsx
index b4090a181..ca8c8b145 100644
--- a/web/app/knowledge/page.tsx
+++ b/web/app/knowledge/page.tsx
@@ -1282,10 +1282,7 @@ export default function KnowledgePage() {
<>
<option value="llamaindex">LlamaIndex</option>
<option value="lightrag">LightRAG</option>
- <option value="raganything">RAG-Anything (MinerU)</option>
- <option value="raganything_docling">
- RAG-Anything (Docling)
- </option>
+ <option value="raganything">RAG-Anything</option>
</>
)}
</select>
@@ -1306,9 +1303,7 @@ export default function KnowledgePage() {
lightrag:
"Lightweight knowledge graph retrieval, fast processing of text documents.",
raganything:
- "Multimodal document processing with MinerU parser. Best for academic PDFs with complex equations.",
- raganything_docling:
- "Multimodal document processing with Docling parser. Better for Office documents and HTML.",
+ "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
};
return (
fallbackDescriptions[ragProvider] ||
@@ -1495,10 +1490,7 @@ export default function KnowledgePage() {
<>
<option value="llamaindex">LlamaIndex</option>
<option value="lightrag">LightRAG</option>
- <option value="raganything">RAG-Anything (MinerU)</option>
- <option value="raganything_docling">
- RAG-Anything (Docling)
- </option>
+ <option value="raganything">RAG-Anything</option>
</>
)}
</select>
@@ -1518,9 +1510,7 @@ export default function KnowledgePage() {
lightrag:
"Lightweight knowledge graph retrieval, fast processing of text documents.",
raganything:
- "Multimodal document processing with MinerU parser. Best for academic PDFs with complex equations.",
- raganything_docling:
- "Multimodal document processing with Docling parser. Better for Office documents and HTML.",
+ "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
};
return (
fallbackDescriptions[ragProvider] ||
diff --git a/web/app/settings/components/ConfigForm.tsx b/web/app/settings/components/ConfigForm.tsx
index e4b0d329e..de398cd93 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={Number.isNaN(dimensions) ? "" : dimensions}
- onChange={(e) => setDimensions(parseInt(e.target.value, 10))}
+ value={dimensions}
+ onChange={(e) => setDimensions(parseInt(e.target.value))}
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>