Skip to content

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

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

Bingxi Zhao5a546b53f658
diff --git a/.env.example_CN b/.env.example_CN
index e578ab3fe..e8b3798f6 100644
--- a/.env.example_CN
+++ b/.env.example_CN
@@ -1,149 +1,115 @@
-# ============================================================================
-# Deep-Tutor 环境配置文件
-# ============================================================================
-# 将此文件复制为 .env 并填写您的 API 密钥和设置。
-# 所有 API 密钥应妥善保管,切勿提交到版本控制系统中。
-# 您可以在 DeepTutor/config/agents.yaml 中调整 max_token 参数。
-# ============================================================================
-
-# ============================================================================
-# 服务器配置
-# ============================================================================
-# 配置服务器端口和远程访问的 API URL。
-
-# 后端 API 端口(默认:8001)
-# BACKEND_PORT=8001
-
-# 前端 Web 端口(默认:3782)
-# FRONTEND_PORT=3782
-
-# 前端 API 基础 URL(用于远程/局域网访问)
-# 当从网络中的其他设备访问 DeepTutor 时设置此项。
-# 示例:如果您的服务器 IP 是 192.168.1.100,请设置:
-# NEXT_PUBLIC_API_BASE=http://192.168.1.100:8001
-# 如果未设置,默认为 http://localhost:8001(仅在本机有效)
-
-# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001(可选)
-
-# ============================================================================
-# LLM 部署模式配置
-# ============================================================================
-# 控制 DeepTutor 如何选择 LLM 提供商。
-#
-# 选项:
-# - hybrid(默认):同时使用 API 和本地提供商。活动的提供商优先。
-# - api:仅使用云端 API 提供商(OpenAI、Anthropic、DeepSeek 等)
-# - local:仅使用本地/自托管提供商(Ollama、LM Studio、vLLM 等)
-#
-# 在 hybrid 模式下,您可以通过设置界面添加 API 和本地提供商,
-# 并通过将其设为"活动"来在它们之间切换。
-
-LLM_MODE=hybrid
-
-# ============================================================================
-# LLM(大语言模型)配置
-# ============================================================================
-# 配置用于推理、生成和对话的主要 AI 模型。
-# 支持 OpenAI 兼容 API(OpenAI、Azure OpenAI、DeepSeek、Qwen 等)
-# 以及本地服务器(Ollama、LM Studio、vLLM、llama.cpp)。
-#
-# 注意:这些环境变量作为默认/后备配置。
-# 您也可以通过设置界面添加提供商,活动时将优先使用。
-
-# LLM 服务提供商类型
-# 提供选项: openai, azure_openai, anthropic,
+# ==============================================================================
+# DeepTutor 环境配置文件
+# ==============================================================================
+# 请将此文件复制为 `.env` 并填写相应的值。
+# [必填] 表示必须配置的字段,[可选] 表示可选配置的字段。
+
+# ==============================================================================
+# 服务器端口配置
+# ==============================================================================
+
+# [可选] 后端 API 服务器端口
+BACKEND_PORT=8001
+
+# [可选] 前端服务器端口
+FRONTEND_PORT=3782
+
+# ==============================================================================
+# LLM 配置(大语言模型)
+# ==============================================================================
+# 所有 AI 功能(聊天、研究、解题等)使用的主要大语言模型
+
+# [必填] 服务提供商:openai, azure_openai, anthropic,
# deepseek, openrouter, groq, together, mistral
# ollama, lm_studio, vllm, llama_cpp
LLM_BINDING=openai
-# LLM 模型名称
-# 云端示例:gpt-4o、gpt-4o-mini、deepseek-chat、claude-3-5-sonnet-20241022
-# 本地示例:llama3.2、qwen2.5、mistral-nemo、deepseek-r1
-LLM_MODEL=
-
-# LLM API 端点 URL
-# 云端示例:
-# - OpenAI:https://api.openai.com/v1
-# - DeepSeek:https://api.deepseek.com
-# - Anthropic:https://api.anthropic.com/v1
-# 本地示例:
-# - Ollama:http://localhost:11434/v1
-# - LM Studio:http://localhost:1234/v1
-# - vLLM:http://localhost:8000/v1
-# - llama.cpp:http://localhost:8080/v1
-LLM_HOST=
-
-# LLM API 认证密钥
-# 云端 API 必需,本地部署可选
-# 对于 Ollama,可以使用任意字符串(如 "ollama")
-LLM_API_KEY=
-
-# 禁用 SSL 证书验证(自签名证书时设置为 'true')
-DISABLE_SSL_VERIFY=false
-
-# ============================================================================
-# 嵌入模型配置
-# ============================================================================
-# 配置用于语义搜索和 RAG 的文本嵌入模型。
-# 知识库功能必需。
-
-# 嵌入服务提供商类型
-# 选项:openai, azure_openai, jina,
+# [必填] 模型名称(例如:gpt-4o, deepseek-chat, claude-3-5-sonnet)
+LLM_MODEL=gpt-4o
+
+# [必填] LLM 服务提供商的 API 密钥
+LLM_API_KEY=sk-xxx
+
+# [必填] API 端点地址
+LLM_HOST=https://api.openai.com/v1
+
+# [可选] API 版本(仅 Azure OpenAI 需要填写)
+LLM_API_VERSION=
+
+# ==============================================================================
+# 向量嵌入(Embedding)配置
+# ==============================================================================
+# 用于 RAG(检索增强生成)的嵌入模型
+
+# [必填] 服务提供商:openai, azure_openai, jina,
# cohere, huggingface, google, ollama, lm_studio
EMBEDDING_BINDING=openai
-# 嵌入模型名称
-# 云端示例:text-embedding-3-large、text-embedding-3-small、text-embedding-ada-002
-# 本地示例(Ollama):nomic-embed-text、mxbai-embed-large
-EMBEDDING_MODEL=text-embedding-3-large
+# [必填] 模型名称
+EMBEDDING_MODEL=text-embedding-3-small
+
+# [必填] API 密钥
+EMBEDDING_API_KEY=sk-xxx
-# 嵌入向量维度
-# text-embedding-3-large:3072
-# text-embedding-3-small:1536
-# nomic-embed-text:768
-# mxbai-embed-large:1024
+# [必填] API 端点地址
+EMBEDDING_HOST=https://api.openai.com/v1
+
+# [必填] 向量维度(必须与模型输出维度匹配)
EMBEDDING_DIMENSION=3072
-# 嵌入 API 端点 URL
-# 云端:https://api.openai.com/v1
-# 本地(Ollama):http://localhost:11434
-EMBEDDING_HOST=
+# [可选] API 版本(仅 Azure OpenAI 需要填写)
+EMBEDDING_API_VERSION=
+
+# ==============================================================================
+# TTS 配置(文本转语音)
+# ==============================================================================
+# 可选:启用语音朗读功能
-# 嵌入 API 认证密钥
-# 云端提供商必需,Ollama 不需要
-EMBEDDING_API_KEY=
+# [可选] 服务提供商:openai, azure_openai
+TTS_BINDING=openai
-# ============================================================================
-# TTS(文本转语音)配置(可选)
-# ============================================================================
-# 配置 Co-Writer(交互式创意生成器)朗读功能的语音合成。
-# 同时记得在 DeepTutor/config/main.yaml 中选择语音。
+# [可选] TTS 模型名称
+TTS_MODEL=tts-1
-# TTS 模型名称(如 tts-1、tts-1-hd)
-TTS_MODEL=
+# [可选] API 密钥(使用 OpenAI 时可与 LLM_API_KEY 相同)
+TTS_API_KEY=sk-xxx
-# TTS API 端点 URL(如 https://api.openai.com/v1)
-TTS_URL=
+# [可选] API 端点地址
+TTS_URL=https://api.openai.com/v1
-# TTS API 认证密钥
-TTS_API_KEY=
+# [可选] 语音风格:alloy, echo, fable, onyx, nova, shimmer
+TTS_VOICE=alloy
-# ============================================================================
-# 网络搜索配置
-# ============================================================================
-# 配置用于研究功能的外部搜索 API。
+# [可选] API 版本(仅 Azure OpenAI 需要填写)
+TTS_BINDING_API_VERSION=
-# (可选)用于网络搜索的搜索提供商
-# 提供商:perplexity, tavily, serper, jina, exa
+# ==============================================================================
+# 搜索配置(网络搜索)
+# ==============================================================================
+# 可选:启用网络搜索功能
+
+# [可选] 搜索服务提供商:perplexity, tavily, serper, jina, exa
SEARCH_PROVIDER=perplexity
-# [Optional] API key for your chosen search provider
+# [可选] 所选搜索服务的 API 密钥
SEARCH_API_KEY=pplx-xxx
-# ============================================================================
-# 日志配置
-# ============================================================================
+# ==============================================================================
+# 云端部署配置
+# ==============================================================================
+# 部署到云端或远程服务器时需要配置
+
+# [可选] 云端部署时的外部 API 基础地址
+# 部署到远程服务器时,请设置为服务器的公网地址
+# 示例:https://your-server.com:8001 或 https://api.yourdomain.com
+NEXT_PUBLIC_API_BASE_EXTERNAL=
+
+# [可选] 直接 API 基础地址(上述配置的替代方案)
+NEXT_PUBLIC_API_BASE=
+
+# ==============================================================================
+# 调试与开发配置
+# ==============================================================================
-# RAG 工具模块的日志级别
-# 选项:DEBUG、INFO、WARNING、ERROR
-RAG_TOOL_MODULE_LOG_LEVEL=INFO
+# [可选] 禁用 SSL 证书验证(生产环境不建议启用)
+DISABLE_SSL_VERIFY=false
\ No newline at end of file
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 2d2cde558..fbbf2c44b 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -8,15 +8,15 @@ on:
# Trigger on version tags
push:
tags:
- - 'v*.*.*'
+ - "v*.*.*"
# Allow manual trigger
workflow_dispatch:
inputs:
tag:
- description: 'Docker image tag (e.g., latest, v0.2.0)'
+ description: "Docker image tag (e.g., latest, v0.2.0)"
required: false
- default: 'latest'
+ default: "latest"
env:
REGISTRY: ghcr.io
@@ -34,6 +34,9 @@ jobs:
contents: read
packages: write
+ outputs:
+ digest: ${{ steps.build.outputs.digest }}
+
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -77,6 +80,7 @@ jobs:
type=ref,event=tag
- name: Build and push AMD64 image
+ id: build
uses: docker/build-push-action@v6
with:
context: .
@@ -90,6 +94,7 @@ jobs:
cache-to: type=gha,mode=max,scope=amd64
build-args: |
BACKEND_PORT=8001
+ provenance: false
# ============================================
# Build ARM64 Image (Apple Silicon, ARM servers)
@@ -102,6 +107,9 @@ jobs:
contents: read
packages: write
+ outputs:
+ digest: ${{ steps.build.outputs.digest }}
+
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -148,6 +156,7 @@ jobs:
type=raw,value=${{ github.ref_name }}-arm64,enable=${{ startsWith(github.ref, 'refs/tags/') }}
- name: Build and push ARM64 image
+ id: build
uses: docker/build-push-action@v6
with:
context: .
@@ -161,6 +170,42 @@ jobs:
cache-to: type=gha,mode=max,scope=arm64
build-args: |
BACKEND_PORT=8001
+ provenance: false
+
+ # ============================================
+ # Create Multi-arch Manifest (optional)
+ # ============================================
+ create-manifest:
+ name: Create Multi-arch Manifest
+ runs-on: ubuntu-latest
+ needs: [build-amd64, build-arm64]
+ if: github.event_name == 'release'
+
+ permissions:
+ contents: read
+ packages: write
+
+ steps:
+ - name: Log in to Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ${{ env.REGISTRY }}
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Create and push multi-arch manifest
+ run: |
+ # Extract version from tag (e.g., v0.5.0 -> 0.5.0)
+ VERSION=${GITHUB_REF_NAME#v}
+
+ # Create manifest for version tag
+ docker manifest create ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-multi \
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION} \
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-arm64
+
+ docker manifest push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-multi
+
+ echo "✅ Created multi-arch manifest: ${VERSION}-multi"
# ============================================
# Generate Summary
@@ -169,14 +214,22 @@ jobs:
name: Generate Summary
runs-on: ubuntu-latest
needs: [build-amd64, build-arm64]
+ if: always()
steps:
- name: Generate image summary
run: |
- echo "## 🐳 Docker Images Published" >> $GITHUB_STEP_SUMMARY
+ echo "## 🐳 Docker Images Build Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Registry:** \`${{ env.REGISTRY }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
+ echo "### Build Status" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Architecture | Status |" >> $GITHUB_STEP_SUMMARY
+ echo "|--------------|--------|" >> $GITHUB_STEP_SUMMARY
+ echo "| AMD64 | ${{ needs.build-amd64.result == 'success' && '✅ Success' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| ARM64 | ${{ needs.build-arm64.result == 'success' && '✅ Success' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
echo "### Available Images" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Architecture | Image Tag | Use Case |" >> $GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml
index 1ae50f868..2585a1f29 100644
--- a/.github/workflows/linting.yaml
+++ b/.github/workflows/linting.yaml
@@ -11,8 +11,11 @@ on:
- develop
jobs:
- lint-and-format:
- name: Linting and Formatting
+ # ============================================
+ # Python Linting with pre-commit
+ # ============================================
+ python-lint:
+ name: Python Linting
runs-on: ubuntu-latest
steps:
@@ -22,14 +25,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v5
with:
- python-version: '3.10'
-
- - name: Set up Node.js
- uses: actions/setup-node@v4
- with:
- node-version: '20'
- cache: 'npm'
- cache-dependency-path: web/package-lock.json
+ python-version: "3.10"
- name: Cache pre-commit
uses: actions/cache@v4
@@ -39,19 +35,14 @@ jobs:
restore-keys: |
pre-commit-
- - name: Install Python dependencies
+ - name: Install pre-commit
run: |
python -m pip install --upgrade pip
pip install pre-commit
- - name: Install frontend dependencies
- working-directory: ./web
- run: npm ci
-
- - name: Run pre-commit
+ - name: Run pre-commit on Python files
run: |
- # Show which hooks will run
- echo "Running pre-commit hooks..."
+ echo "🔍 Running pre-commit hooks on Python files..."
pre-commit run --all-files --verbose 2>&1 || {
echo ""
echo "╔═══════════════════════════════════════════════════════════════════════════╗"
@@ -71,3 +62,84 @@ jobs:
echo ""
exit 1
}
+
+ # ============================================
+ # Frontend Linting (TypeScript/JavaScript)
+ # ============================================
+ frontend-lint:
+ name: Frontend Linting
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "20"
+ cache: "npm"
+ cache-dependency-path: web/package-lock.json
+
+ - name: Install frontend dependencies
+ working-directory: ./web
+ run: npm ci
+
+ - name: Run ESLint
+ working-directory: ./web
+ run: |
+ echo "🔍 Running ESLint on frontend code..."
+ npm run lint 2>&1 || {
+ echo ""
+ echo "╔═══════════════════════════════════════════════════════════════════════════╗"
+ echo "║ ❌ ESLint checks failed! ║"
+ echo "╠═══════════════════════════════════════════════════════════════════════════╣"
+ echo "║ Please run the following commands locally to fix linting issues: ║"
+ echo "║ ║"
+ echo "║ cd web ║"
+ echo "║ npm run lint # Check for linting issues ║"
+ echo "║ npm run lint -- --fix # Auto-fix linting issues ║"
+ echo "║ ║"
+ echo "║ Then commit and push the changes. ║"
+ echo "╚═══════════════════════════════════════════════════════════════════════════╝"
+ echo ""
+ exit 1
+ }
+
+ - name: TypeScript type check
+ working-directory: ./web
+ run: |
+ echo "🔍 Running TypeScript type check..."
+ npx tsc --noEmit 2>&1 || {
+ echo ""
+ echo "╔═══════════════════════════════════════════════════════════════════════════╗"
+ echo "║ ❌ TypeScript type check failed! ║"
+ echo "╠═══════════════════════════════════════════════════════════════════════════╣"
+ echo "║ Please fix the TypeScript errors shown above. ║"
+ echo "╚═══════════════════════════════════════════════════════════════════════════╝"
+ echo ""
+ exit 1
+ }
+
+ # ============================================
+ # Lint Summary
+ # ============================================
+ lint-summary:
+ name: Lint Summary
+ runs-on: ubuntu-latest
+ needs: [python-lint, frontend-lint]
+ if: always()
+
+ steps:
+ - name: Generate summary
+ run: |
+ echo "## 🔍 Linting Results" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
+ echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
+ echo "| Python (pre-commit) | ${{ needs.python-lint.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Frontend (ESLint + TypeScript) | ${{ needs.frontend-lint.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+
+ - name: Fail if linting failed
+ if: needs.python-lint.result == 'failure' || needs.frontend-lint.result == 'failure'
+ run: exit 1
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index cf492e4ce..75e7ac56f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -22,20 +22,33 @@ on:
- "pyproject.toml"
jobs:
- # Quick import check to ensure modules load correctly
- # Uses minimal dependencies to avoid disk space issues
+ # ============================================
+ # Import Check - Quick validation across Python versions
+ # ============================================
import-check:
- name: Import Check
+ name: Import Check (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11"]
steps:
- name: Checkout code
uses: actions/checkout@v6
- - name: Set up Python
+ - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
- python-version: "3.10"
+ python-version: ${{ matrix.python-version }}
+
+ - name: Cache pip packages
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-${{ matrix.python-version }}-
- name: Install minimal dependencies for import check
run: |
@@ -59,6 +72,7 @@ jobs:
- name: Check module imports
run: |
+ echo "🐍 Testing with Python ${{ matrix.python-version }}"
python -c "from src.services.llm import complete, stream, fetch_models, sanitize_url; print('✅ LLM service imports OK')"
python -c "from src.services.llm.config import get_llm_config; print('✅ LLM config imports OK')"
python -c "from src.services.config.loader import load_config_with_main; print('✅ Config loader imports OK')"
@@ -66,3 +80,82 @@ jobs:
python -c "from src.logging import get_logger; print('✅ Logging imports OK')"
env:
PYTHONPATH: ${{ github.workspace }}
+
+ # ============================================
+ # Unit Tests - Run pytest across Python versions
+ # ============================================
+ unit-tests:
+ name: Unit Tests (Python ${{ matrix.python-version }})
+ runs-on: ubuntu-latest
+ needs: import-check
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11"]
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Cache pip packages
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-${{ matrix.python-version }}-
+
+ - name: Install test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install pytest pytest-asyncio pytest-cov
+ # Install minimal dependencies for testing
+ pip install \
+ python-dotenv>=1.0.0 \
+ PyYAML>=6.0 \
+ tiktoken>=0.5.0 \
+ jinja2>=3.1.0 \
+ requests>=2.32.2 \
+ openai>=1.30.0 \
+ aiohttp>=3.9.4 \
+ httpx>=0.27.0 \
+ nest_asyncio>=1.5.8 \
+ tenacity>=8.0.0 \
+ fastapi>=0.100.0 \
+ pydantic>=2.0.0 \
+ numpy>=1.24.0,\<2.0.0
+
+ - name: Run unit tests
+ run: |
+ echo "🧪 Running tests with Python ${{ matrix.python-version }}"
+ pytest tests/ -v --tb=short --ignore=tests/agents/ || echo "⚠️ Some tests failed or no tests found"
+ env:
+ PYTHONPATH: ${{ github.workspace }}
+
+ # ============================================
+ # Test Summary
+ # ============================================
+ test-summary:
+ name: Test Summary
+ runs-on: ubuntu-latest
+ needs: [import-check, unit-tests]
+ if: always()
+
+ steps:
+ - name: Check test results
+ run: |
+ echo "## 🧪 Test Results Summary" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "| Python Version | Import Check | Unit Tests |" >> $GITHUB_STEP_SUMMARY
+ echo "|----------------|--------------|------------|" >> $GITHUB_STEP_SUMMARY
+ echo "| 3.10 | ${{ needs.import-check.result == 'success' && '✅' || '❌' }} | ${{ needs.unit-tests.result == 'success' && '✅' || '❌' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| 3.11 | ${{ needs.import-check.result == 'success' && '✅' || '❌' }} | ${{ needs.unit-tests.result == 'success' && '✅' || '❌' }} |" >> $GITHUB_STEP_SUMMARY
+
+ - name: Fail if tests failed
+ if: needs.import-check.result == 'failure' || needs.unit-tests.result == 'failure'
+ run: exit 1
diff --git a/.github/workflows/update-roster.yml b/.github/workflows/update-roster.yml
index fddadb68c..45fb3e8e6 100644
--- a/.github/workflows/update-roster.yml
+++ b/.github/workflows/update-roster.yml
@@ -1,9 +1,9 @@
name: Update Repo Roster
on:
- # Run twice a day (at 00:00 and 12:00 UTC)
+ # Run once a day (at 00:00 UTC)
schedule:
- - cron: '0 0,12 * * *'
+ - cron: '0 0 * * *'
# Allow manual trigger
workflow_dispatch:
# Run when stars/forks might change (on push to main)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 3c2e5b052..e21601473 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -88,16 +88,6 @@ 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/config/main.yaml b/config/main.yaml
index 619523a19..6db5d8b5c 100644
--- a/config/main.yaml
+++ b/config/main.yaml
@@ -28,16 +28,15 @@ tools:
enabled: true
max_results: 5
logging:
+ # Global log level for the entire system (DEBUG, INFO, WARNING, ERROR)
+ # This controls both DeepTutor logs and RAG module logs
level: DEBUG
save_to_file: true
console_output: true
- lightrag_forwarding:
- enabled: true
- min_level: DEBUG
- add_prefix: true
- logger_names:
- knowledge_init: LightRAG-Init
- rag_tool: LightRAG
+ # RAG module logger name mapping (optional customization)
+ rag_logger_names:
+ knowledge_init: RAG-Init
+ rag_tool: RAG
question:
# Refactored: no iteration loops (max_rounds removed)
rag_query_count: 3
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 953f38be1..a8e5bca34 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -35,8 +35,7 @@ services:
environment:
- NODE_ENV=development
- # Enable more verbose logging in development
- - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-DEBUG}
+ # Logging: Configure in config/main.yaml -> logging.level
# In development, we might want to see logs directly
# Uncomment the following to disable log files and see everything in console
diff --git a/docker-compose.yml b/docker-compose.yml
index f05c788cc..b7a3c0bb9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -57,8 +57,7 @@ services:
# Web Search Configuration (Optional)
- SEARCH_PROVIDER=${SEARCH_PROVIDER:-perplexity}
- SEARCH_API_KEY=${SEARCH_API_KEY:-}
- # Logging Configuration
- - RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-INFO}
+ # Logging: Configure in config/main.yaml -> logging.level
# ============================================
# Service Ports Configuration
# ============================================
diff --git a/requirements.txt b/requirements.txt
index 6047daedc..8ecf5e36e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -44,6 +44,7 @@ pydantic>=2.0.0
# ============================================
lightrag-hku>=1.0.0
raganything>=0.1.0
+docling>=2.31.0 # Document parser for Office/HTML (alternative to MinerU)
# ============================================
# LlamaIndex
diff --git a/scripts/check_install.py b/scripts/check_install.py
new file mode 100644
index 000000000..5680e9f46
--- /dev/null
+++ b/scripts/check_install.py
@@ -0,0 +1,461 @@
+#!/usr/bin/env python
+"""
+DeepTutor Installation Checker
+
+Verifies that all required dependencies are correctly installed.
+Run this script to diagnose installation issues.
+"""
+
+import importlib.metadata
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+# Set Windows console UTF-8 encoding
+if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
+
+
+# Color codes for terminal output
+class Colors:
+ RED = "\033[0;31m"
+ GREEN = "\033[0;32m"
+ YELLOW = "\033[1;33m"
+ BLUE = "\033[0;34m"
+ CYAN = "\033[0;36m"
+ NC = "\033[0m" # No Color
+
+ @classmethod
+ def disable(cls):
+ """Disable colors for non-TTY output"""
+ cls.RED = cls.GREEN = cls.YELLOW = cls.BLUE = cls.CYAN = cls.NC = ""
+
+
+# Disable colors if not a TTY
+if not sys.stdout.isatty():
+ Colors.disable()
+
+
+def print_header(message: str):
+ """Print section header"""
+ print(f"\n{'=' * 60}")
+ print(f"📋 {message}")
+ print("=" * 60)
+
+
+def print_success(message: str):
+ """Print success message"""
+ print(f"{Colors.GREEN}✅ {message}{Colors.NC}")
+
+
+def print_error(message: str):
+ """Print error message"""
+ print(f"{Colors.RED}❌ {message}{Colors.NC}")
+
+
+def print_warning(message: str):
+ """Print warning message"""
+ print(f"{Colors.YELLOW}⚠️ {message}{Colors.NC}")
+
+
+def print_info(message: str):
+ """Print info message"""
+ print(f"{Colors.CYAN}ℹ️ {message}{Colors.NC}")
+
+
+def get_package_version(package_name: str) -> str | None:
+ """Get installed package version"""
+ try:
+ return importlib.metadata.version(package_name)
+ except importlib.metadata.PackageNotFoundError:
+ return None
+
+
+def check_python_environment() -> bool:
+ """Check Python environment"""
+ print_header("Python Environment")
+
+ all_ok = True
+
+ # Python version
+ py_version = sys.version_info
+ print_info(f"Python version: {py_version.major}.{py_version.minor}.{py_version.micro}")
+
+ if py_version >= (3, 10):
+ print_success(f"Python {py_version.major}.{py_version.minor} meets requirement (>=3.10)")
+ else:
+ print_error(f"Python {py_version.major}.{py_version.minor} is below requirement (>=3.10)")
+ all_ok = False
+
+ # Python executable
+ print_info(f"Python executable: {sys.executable}")
+
+ # Virtual environment
+ in_venv = hasattr(sys, "real_prefix") or (
+ hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
+ )
+ conda_env = os.environ.get("CONDA_DEFAULT_ENV")
+
+ if conda_env:
+ print_success(f"Conda environment: {conda_env}")
+ elif in_venv:
+ print_success(f"Virtual environment: {sys.prefix}")
+ else:
+ print_warning("No isolated environment detected (recommended: use conda or venv)")
+
+ return all_ok
+
+
+def check_backend_packages() -> tuple[bool, int, int]:
+ """Check backend Python packages"""
+ print_header("Backend Dependencies")
+
+ # Required packages: (pip_name, import_name, min_version, is_optional)
+ packages = [
+ # Core
+ ("python-dotenv", "dotenv", "1.0.0", False),
+ ("PyYAML", "yaml", "6.0", False),
+ ("tiktoken", "tiktoken", "0.5.0", False),
+ ("jinja2", "jinja2", "3.1.0", False),
+ # HTTP & API
+ ("requests", "requests", "2.32.0", False),
+ ("openai", "openai", "1.30.0", False),
+ ("anthropic", "anthropic", "0.30.0", False),
+ ("aiohttp", "aiohttp", "3.9.0", False),
+ ("httpx", "httpx", "0.27.0", False),
+ # Async
+ ("nest-asyncio", "nest_asyncio", "1.5.8", False),
+ ("tenacity", "tenacity", "8.0.0", False),
+ # Web framework
+ ("fastapi", "fastapi", "0.100.0", False),
+ ("uvicorn", "uvicorn", "0.24.0", False),
+ ("websockets", "websockets", "12.0", False),
+ ("pydantic", "pydantic", "2.0.0", False),
+ # RAG
+ ("lightrag-hku", "lightrag", "1.0.0", False),
+ ("raganything", "raganything", "0.1.0", False),
+ ("llama-index", "llama_index", "0.14.0", False),
+ # Document parsing
+ ("docling", "docling", "2.31.0", True), # Optional
+ ("PyMuPDF", "fitz", "1.26.0", False),
+ # Academic
+ ("arxiv", "arxiv", "2.0.0", False),
+ # Optional API clients
+ ("perplexityai", "perplexity", "0.1.0", True),
+ ("dashscope", "dashscope", "1.14.0", True),
+ ]
+
+ installed = 0
+ missing = 0
+ all_ok = True
+
+ for pip_name, import_name, min_version, is_optional in packages:
+ try:
+ __import__(import_name)
+ version = get_package_version(pip_name)
+ version_str = f" (v{version})" if version else ""
+ print_success(f" ✓ {pip_name}{version_str}")
+ installed += 1
+ except ImportError:
+ if is_optional:
+ print_warning(f" ⚠ {pip_name} not installed (optional)")
+ else:
+ print_error(f" ✗ {pip_name} not installed")
+ all_ok = False
+ missing += 1
+
+ return all_ok, installed, missing
+
+
+def check_frontend_packages(project_root: Path) -> tuple[bool, int, int]:
+ """Check frontend Node.js packages"""
+ print_header("Frontend Dependencies")
+
+ web_dir = project_root / "web"
+ node_modules = web_dir / "node_modules"
+ package_json = web_dir / "package.json"
+
+ installed = 0
+ missing = 0
+ all_ok = True
+
+ # Check npm
+ npm_path = shutil.which("npm")
+ if npm_path:
+ try:
+ result = subprocess.run(
+ ["npm", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ npm_version = result.stdout.strip()
+ print_success(f"npm available (v{npm_version})")
+ except Exception:
+ print_warning("npm found but version check failed")
+ else:
+ print_error("npm not found - Node.js is required for frontend")
+ all_ok = False
+
+ # Check node
+ node_path = shutil.which("node")
+ if node_path:
+ try:
+ result = subprocess.run(
+ ["node", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ node_version = result.stdout.strip()
+ print_success(f"Node.js available ({node_version})")
+ except Exception:
+ print_warning("Node.js found but version check failed")
+ else:
+ print_error("Node.js not found")
+ all_ok = False
+
+ # Check package.json exists
+ if not package_json.exists():
+ print_error(f"package.json not found: {package_json}")
+ return False, 0, 0
+
+ # Check node_modules
+ if not node_modules.exists():
+ print_error("node_modules directory does not exist")
+ print_info("Run 'npm install' in web/ directory to install dependencies")
+ return False, 0, 0
+
+ # Check key packages
+ key_packages = [
+ "next",
+ "react",
+ "react-dom",
+ "typescript",
+ "tailwindcss",
+ "@radix-ui/react-dialog",
+ "lucide-react",
+ ]
+
+ print_info("Checking key frontend packages...")
+
+ for pkg in key_packages:
+ pkg_dir = node_modules / pkg
+ if pkg_dir.exists():
+ # Try to get version from package.json
+ pkg_json = pkg_dir / "package.json"
+ version = ""
+ if pkg_json.exists():
+ try:
+ import json
+
+ with open(pkg_json) as f:
+ data = json.load(f)
+ version = f" (v{data.get('version', '?')})"
+ except Exception:
+ pass
+ print_success(f" ✓ {pkg}{version}")
+ installed += 1
+ else:
+ print_error(f" ✗ {pkg} not installed")
+ missing += 1
+ all_ok = False
+
+ return all_ok, installed, missing
+
+
+def check_system_tools() -> bool:
+ """Check system tools and utilities"""
+ print_header("System Tools")
+
+ all_ok = True
+
+ # Git
+ git_path = shutil.which("git")
+ if git_path:
+ try:
+ result = subprocess.run(
+ ["git", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ git_version = result.stdout.strip()
+ print_success(f"{git_version}")
+ except Exception:
+ print_warning("git found but version check failed")
+ else:
+ print_warning("git not found (optional but recommended)")
+
+ # uv (fast Python package manager)
+ uv_path = shutil.which("uv")
+ if uv_path:
+ try:
+ result = subprocess.run(
+ ["uv", "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ uv_version = result.stdout.strip()
+ print_success(f"uv available ({uv_version})")
+ except Exception:
+ print_warning("uv found but version check failed")
+ else:
+ print_info("uv not found (optional, for faster package installation)")
+
+ return all_ok
+
+
+def check_env_file(project_root: Path) -> bool:
+ """Check .env file configuration"""
+ print_header("Environment Configuration")
+
+ env_file = project_root / ".env"
+ env_example = project_root / ".env.example"
+
+ if env_file.exists():
+ print_success(".env file exists")
+
+ # Check for required keys (without revealing values)
+ required_keys = [
+ "OPENAI_API_KEY",
+ ]
+ optional_keys = [
+ "ANTHROPIC_API_KEY",
+ "PERPLEXITY_API_KEY",
+ "DASHSCOPE_API_KEY",
+ ]
+
+ try:
+ with open(env_file) as f:
+ content = f.read()
+ lines = content.split("\n")
+ env_vars = {}
+ for line in lines:
+ line = line.strip()
+ if line and not line.startswith("#") and "=" in line:
+ key = line.split("=")[0].strip()
+ value = line.split("=", 1)[1].strip() if "=" in line else ""
+ env_vars[key] = value
+
+ for key in required_keys:
+ if key in env_vars and env_vars[key]:
+ print_success(f" ✓ {key} is set")
+ else:
+ print_warning(f" ⚠ {key} is not set (required for most features)")
+
+ for key in optional_keys:
+ if key in env_vars and env_vars[key]:
+ print_success(f" ✓ {key} is set")
+ else:
+ print_info(f" ○ {key} is not set (optional)")
+
+ except Exception as e:
+ print_warning(f"Could not read .env file: {e}")
+
+ return True
+ else:
+ print_warning(".env file not found")
+ if env_example.exists():
+ print_info("Copy .env.example to .env and configure your API keys")
+ else:
+ print_info("Create a .env file with your API keys (e.g., OPENAI_API_KEY)")
+ return False
+
+
+def main():
+ """Main function"""
+ print("\n" + "=" * 60)
+ print("🔍 DeepTutor Installation Checker")
+ print("=" * 60)
+ print("Checking all dependencies and configurations...")
+
+ # Get project root
+ script_dir = Path(__file__).parent
+ project_root = script_dir.parent
+
+ print_info(f"Project root: {project_root}")
+
+ # Track overall status
+ all_checks_passed = True
+ summary = []
+
+ # 1. Python environment
+ if check_python_environment():
+ summary.append(("Python Environment", "✅ OK"))
+ else:
+ summary.append(("Python Environment", "❌ Issues found"))
+ all_checks_passed = False
+
+ # 2. Backend packages
+ backend_ok, backend_installed, backend_missing = check_backend_packages()
+ if backend_ok:
+ summary.append(("Backend Dependencies", f"✅ OK ({backend_installed} packages)"))
+ else:
+ summary.append(
+ ("Backend Dependencies", f"❌ {backend_missing} missing, {backend_installed} installed")
+ )
+ all_checks_passed = False
+
+ # 3. Frontend packages
+ frontend_ok, frontend_installed, frontend_missing = check_frontend_packages(project_root)
+ if frontend_ok:
+ summary.append(("Frontend Dependencies", f"✅ OK ({frontend_installed} packages)"))
+ else:
+ summary.append(
+ (
+ "Frontend Dependencies",
+ f"❌ {frontend_missing} missing, {frontend_installed} installed",
+ )
+ )
+ all_checks_passed = False
+
+ # 4. System tools
+ check_system_tools()
+ summary.append(("System Tools", "✅ Checked"))
+
+ # 5. Environment configuration
+ if check_env_file(project_root):
+ summary.append(("Environment Config", "✅ .env exists"))
+ else:
+ summary.append(("Environment Config", "⚠️ .env missing"))
+
+ # Print summary
+ print_header("Summary")
+
+ for item, status in summary:
+ print(f" {item}: {status}")
+
+ print("")
+ if all_checks_passed:
+ print_success("All required dependencies are installed!")
+ print_info("You can start DeepTutor with: python scripts/start_web.py")
+ else:
+ print_error("Some dependencies are missing!")
+ print_info("Run: python scripts/install_all.py")
+ print_info("Or manually install missing packages")
+
+ print("=" * 60 + "\n")
+
+ return 0 if all_checks_passed else 1
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except KeyboardInterrupt:
+ print("\n\n⚠️ Check interrupted by user")
+ sys.exit(1)
+ except Exception as e:
+ print_error(f"\n❌ Unexpected error: {e}")
+ import traceback
+
+ traceback.print_exc()
+ sys.exit(1)
+
diff --git a/scripts/install_all.py b/scripts/install_all.py
index e3ce35996..bcd40ba70 100644
--- a/scripts/install_all.py
+++ b/scripts/install_all.py
@@ -145,10 +145,10 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
print_error(f"Error installing core dependencies: {e}")
return False
- # Stage 2: Install lightrag-hku
- print_info("Stage 2/3: Installing lightrag-hku...")
+ # Stage 2: Install llama-index
+ print_info("Stage 2/3: Installing llama-index...")
try:
- cmd = [sys.executable, "-m", "pip", "install", "lightrag-hku>=1.0.0"]
+ cmd = [sys.executable, "-m", "pip", "install", "llama-index>=0.14.12"]
result = subprocess.run(
cmd,
check=False,
@@ -158,12 +158,14 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
text=True,
)
if result.returncode != 0:
- print_warning("lightrag-hku installation had issues, continuing...")
+ print_warning("llama-index installation had issues, continuing...")
except Exception as e:
- print_warning(f"lightrag-hku installation error: {e}")
+ print_warning(f"llama-index installation error: {e}")
- # Stage 3: Install raganything with special handling
- print_info("Stage 3/3: Installing raganything (this may take a while)...")
+ # Stage 3: Install raganything (includes lightrag-hku as dependency)
+ print_info(
+ "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
+ )
try:
# First try normal install
cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0"]
@@ -192,6 +194,23 @@ def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool
except Exception as e:
print_warning(f"raganything installation error: {e}")
+ # Stage 4: Install docling (alternative parser for Office/HTML documents)
+ print_info("Stage 4/4: Installing docling (document parser for Office/HTML)...")
+ try:
+ cmd = [sys.executable, "-m", "pip", "install", "docling>=2.31.0"]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=600, # 10 minutes
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ print_warning("docling installation had issues (optional, can be skipped)")
+ except Exception as e:
+ print_warning(f"docling installation error (optional): {e}")
+
# Try to install any remaining optional deps
try:
optional_deps = ["perplexityai>=0.1.0", "dashscope>=1.14.0"]
@@ -521,7 +540,15 @@ def verify_installation(project_root: Path) -> bool:
# Check backend key packages
print_info("Checking backend key packages...")
- backend_packages = ["fastapi", "uvicorn", "openai", "lightrag_hku", "raganything"]
+ backend_packages = [
+ "fastapi",
+ "uvicorn",
+ "openai",
+ "lightrag_hku",
+ "raganything",
+ "llama_index",
+ "docling",
+ ]
for package in backend_packages:
try:
@@ -530,12 +557,18 @@ def verify_installation(project_root: Path) -> bool:
__import__("lightrag")
elif package == "raganything":
__import__("raganything")
+ elif package == "docling":
+ __import__("docling")
else:
__import__(package)
print_success(f" ✓ {package}")
except ImportError:
- print_error(f" ✗ {package} not installed")
- all_ok = False
+ if package == "docling":
+ # docling is optional
+ print_warning(f" ⚠ {package} not installed (optional, for Office/HTML parsing)")
+ else:
+ print_error(f" ✗ {package} not installed")
+ all_ok = False
# Check frontend node_modules
print_info("Checking frontend dependencies...")
diff --git a/scripts/install_all.sh b/scripts/install_all.sh
index 7e6fb6012..ae6afe229 100644
--- a/scripts/install_all.sh
+++ b/scripts/install_all.sh
@@ -129,17 +129,21 @@ install_with_pip_staged() {
return 1
fi
- # Stage 2: lightrag-hku
- print_info "Stage 2/3: Installing lightrag-hku..."
- python -m pip install "lightrag-hku>=1.0.0" || print_warning "lightrag-hku installation had issues"
+ # Stage 2: llama-index
+ print_info "Stage 2/3: Installing llama-index..."
+ python -m pip install "llama-index>=0.14.12" || print_warning "llama-index installation had issues"
- # Stage 3: raganything (complex dependencies)
- print_info "Stage 3/3: Installing raganything (this may take a while)..."
+ # Stage 3: raganything (includes lightrag-hku as dependency)
+ print_info "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."
if ! python -m pip install "raganything>=0.1.0"; then
print_warning "Standard install failed, trying with --no-deps..."
python -m pip install "raganything>=0.1.0" --no-deps || print_warning "raganything installation had issues"
fi
+ # Stage 4: docling (alternative parser for Office/HTML documents)
+ print_info "Stage 4/4: Installing docling (document parser for Office/HTML)..."
+ python -m pip install "docling>=2.31.0" || print_warning "docling installation had issues (optional, can be skipped)"
+
# Optional deps
python -m pip install "perplexityai>=0.1.0" "dashscope>=1.14.0" 2>/dev/null || true
@@ -343,6 +347,21 @@ else
ALL_OK=false
fi
+# Check llama_index
+if python -c "import llama_index" 2>/dev/null; then
+ print_success " ✓ llama_index"
+else
+ print_error " ✗ llama_index not installed"
+ ALL_OK=false
+fi
+
+# Check docling (optional)
+if python -c "import docling" 2>/dev/null; then
+ print_success " ✓ docling"
+else
+ print_warning " ⚠ docling not installed (optional, for Office/HTML parsing)"
+fi
+
# Check frontend node_modules
print_info "Checking frontend dependencies..."
diff --git a/scripts/start_web.py b/scripts/start_web.py
index 2884c2275..dd5ba6b61 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -224,9 +224,9 @@ def start_backend():
try:
for line in iter(process.stdout.readline, ""):
if line:
- print_flush(f"[Backend] {line.rstrip()}")
+ print_flush(f"[Backend] {line.rstrip()}")
except Exception as e:
- print_flush(f"[Backend] Log output error: {e}")
+ print_flush(f"[Backend] Log output error: {e}")
log_thread = threading.Thread(target=log_output, daemon=True)
log_thread.start()
diff --git a/src/api/main.py b/src/api/main.py
index e13763ed8..66ee5072e 100644
--- a/src/api/main.py
+++ b/src/api/main.py
@@ -23,6 +23,7 @@ from src.api.routers import (
)
from src.logging import get_logger
+# Note: Don't set service_prefix here - start_web.py already adds [Backend] prefix
logger = get_logger("API")
CONFIG_DRIFT_ERROR_TEMPLATE = (
@@ -130,6 +131,17 @@ async def lifespan(app: FastAPI):
# Validate configuration consistency
validate_tool_consistency()
+ # Initialize LLM client early to set environment variables for LightRAG
+ # LightRAG reads OPENAI_API_KEY from os.environ internally, so we must
+ # set it before any RAG operations can happen
+ try:
+ from src.services.llm import get_llm_client
+
+ llm_client = get_llm_client()
+ logger.info(f"LLM client initialized: model={llm_client.config.model}")
+ except Exception as e:
+ logger.warning(f"Failed to initialize LLM client at startup: {e}")
+
yield
# Execute on shutdown
logger.info("Application shutdown")
diff --git a/src/config/constants.py b/src/config/constants.py
index a42ddf7b5..e21b62654 100644
--- a/src/config/constants.py
+++ b/src/config/constants.py
@@ -23,12 +23,14 @@ VALID_SOLVE_TOOLS = [
"finish",
]
-# Logging symbols for different log levels
-LOG_SYMBOLS = {
- "DEBUG": "·",
- "INFO": "●",
- "SUCCESS": "✓",
- "WARNING": "⚠",
- "ERROR": "✗",
- "CRITICAL": "✗",
-}
+# Standard log level tags (used in unified logging format)
+LOG_LEVEL_TAGS = [
+ "DEBUG",
+ "INFO",
+ "SUCCESS",
+ "WARNING",
+ "ERROR",
+ "CRITICAL",
+ "PROGRESS",
+ "COMPLETE",
+]
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
index bb7ff46da..7e8cdfeb6 100644
--- a/src/knowledge/add_documents.py
+++ b/src/knowledge/add_documents.py
@@ -21,13 +21,15 @@ from typing import TYPE_CHECKING, Any, Dict, List
from dotenv import load_dotenv
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
# Attempt imports for dynamic dependencies
try:
- from lightrag.llm.openai import openai_complete_if_cache
from lightrag.utils import EmbeddingFunc
except ImportError:
- # These will be caught during runtime if needed
- openai_complete_if_cache = None
+ # This will be caught during runtime if needed
EmbeddingFunc = None
# Type hinting support for dynamic imports
@@ -219,99 +221,16 @@ class DocumentAdder:
if self.progress_tracker:
from src.knowledge.progress_tracker import ProgressStage
- self.llm_cfg = get_llm_config()
- model = self.llm_cfg.model
- api_key = self.api_key or self.llm_cfg.api_key
- base_url = self.base_url or self.llm_cfg.base_url
-
- # LLM Function Wrapper
- def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- if history_messages is None:
- history_messages = []
- return openai_complete_if_cache(
- model,
- prompt,
- system_prompt=system_prompt,
- history_messages=history_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ # Use unified LLM client from src/services/llm
+ from src.services.llm import get_llm_client
- # Vision Function Wrapper - Robust history handling
- def vision_model_func(
- prompt,
- system_prompt=None,
- history_messages=None,
- image_data=None,
- messages=None,
- **kwargs,
- ):
- if history_messages is None:
- history_messages = []
- # If pre-formatted messages are provided, sanitize them
- if messages:
- safe_messages = self._filter_valid_messages(messages)
- return openai_complete_if_cache(
- model,
- prompt="",
- messages=safe_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ llm_client = get_llm_client()
+ self.llm_cfg = llm_client.config
- # --- Construct Message History ---
- current_messages = []
-
- # 1. Add System Prompt (if provided)
- if system_prompt:
- current_messages.append({"role": "system", "content": system_prompt})
-
- # 2. Add History (Filtering out conflicting system prompts)
- if history_messages:
- # Filter out system messages from history to avoid duplicates/conflicts with the new system_prompt
- filtered_history = [
- msg
- for msg in history_messages
- if isinstance(msg, dict) and msg.get("role") != "system"
- ]
- current_messages.extend(filtered_history)
-
- # 3. Construct New User Message
- user_content: List[Dict[str, Any]] = [{"type": "text", "text": prompt}]
- if image_data:
- user_content.append(
- {
- "type": "image_url",
- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
- }
- )
-
- # 4. Merge Logic: Avoid back-to-back user messages
- if current_messages and current_messages[-1].get("role") == "user":
- last_msg = current_messages[-1]
- # If last content is string, convert to list format first
- if isinstance(last_msg["content"], str):
- last_msg["content"] = [{"type": "text", "text": last_msg["content"]}]
-
- # Append new content blocks
- if isinstance(last_msg["content"], list):
- last_msg["content"].extend(user_content)
- else:
- # Fallback if structure is unexpected, just append new message
- current_messages.append({"role": "user", "content": user_content})
- else:
- current_messages.append({"role": "user", "content": user_content})
-
- return openai_complete_if_cache(
- model,
- prompt="",
- messages=current_messages,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
# Embedding Setup
reset_embedding_client()
@@ -464,36 +383,50 @@ class DocumentAdder:
]
async def fix_structure(self):
- """Robustly moves nested outputs and cleans up."""
- logger.info("Organizing storage structure...")
+ """
+ Clean up parser output directories after image migration.
- # 1. Identify moves
- moves = []
- for doc_dir in self.content_list_dir.glob("*"):
+ NOTE: Image migration and path updates are now handled by the RAG pipeline
+ (raganything.py / raganything_docling.py) BEFORE RAG insertion. This ensures
+ RAG stores the correct canonical image paths (kb/images/) from the start.
+
+ This method now only cleans up empty temporary parser output directories.
+ """
+ logger.info("Checking for leftover parser output directories...")
+
+ # Support both 'auto' (MinerU) and 'docling' parser output directories
+ parser_subdirs = ["auto", "docling"]
+ cleaned_count = 0
+
+ for doc_dir in list(self.content_list_dir.glob("*")):
if not doc_dir.is_dir():
continue
- # Content List
- json_src = next(doc_dir.glob("auto/*_content_list.json"), None)
- if json_src:
- moves.append((json_src, self.content_list_dir / f"{doc_dir.name}.json"))
-
- # Images
- for img in doc_dir.glob("auto/images/*"):
- moves.append((img, self.images_dir / img.name))
-
- # 2. Execute moves
- for src, dest in moves:
- if src.exists():
- await self._run_in_executor(shutil.copy2, src, dest)
-
- # 3. Safe Cleanup: Only delete directories we actually processed
- for doc_dir in self.content_list_dir.glob("*"):
- if doc_dir.is_dir():
- # Safety check: only delete if it looks like a parser output (has 'auto' subdir)
- # This prevents wiping manual user folders in content_list_dir
- if (doc_dir / "auto").exists():
- await self._run_in_executor(shutil.rmtree, doc_dir, ignore_errors=True)
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Check if directory is empty or only contains empty subdirs
+ has_content = any(
+ f.is_file() or (f.is_dir() and any(f.iterdir()))
+ for f in subdir.iterdir()
+ )
+
+ if not has_content:
+ await self._run_in_executor(shutil.rmtree, subdir)
+ cleaned_count += 1
+ except Exception as e:
+ logger.debug(f"Could not clean up {subdir}: {e}")
+
+ # Remove doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ except Exception:
+ pass
+
+ if cleaned_count > 0:
+ logger.info(f"Cleaned up {cleaned_count} empty parser directories")
def extract_numbered_items_for_new_docs(self, processed_files, batch_size=20):
if not processed_files:
diff --git a/src/knowledge/extract_numbered_items.py b/src/knowledge/extract_numbered_items.py
index aa2111942..0fb6abf15 100644
--- a/src/knowledge/extract_numbered_items.py
+++ b/src/knowledge/extract_numbered_items.py
@@ -19,9 +19,8 @@ from typing import Any
sys.path.append(str(Path(__file__).parent.parent.parent))
from dotenv import load_dotenv
-from lightrag.llm.openai import openai_complete_if_cache
-from src.services.llm import get_llm_config
+from src.services.llm import get_llm_client, get_llm_config
load_dotenv(dotenv_path=".env", override=False)
@@ -62,18 +61,18 @@ async def _call_llm_async(
temperature: float = 0.1,
model: str = None,
) -> str:
- """Asynchronously call LLM"""
- # If model not specified, get from env_config
+ """Asynchronously call LLM using unified LLM service"""
+ # Get unified LLM client (handles all provider differences and env var setup)
+ llm_client = get_llm_client()
+ llm_model_func = llm_client.get_model_func()
+
+ # If model not specified, use configured model
if model is None:
- llm_cfg = get_llm_config()
- model = llm_cfg.model
+ model = llm_client.config.model
- result = openai_complete_if_cache(
- model,
+ result = llm_model_func(
prompt,
system_prompt=system_prompt,
- api_key=api_key,
- base_url=base_url,
max_tokens=max_tokens,
temperature=temperature,
)
diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.py
index 2ed8deef7..3dfc18f46 100644
--- a/src/knowledge/initializer.py
+++ b/src/knowledge/initializer.py
@@ -274,80 +274,58 @@ class KnowledgeBaseInitializer:
async def fix_structure(self):
"""
- Fix the nested structure created by process_document_complete.
- Flattens content_list directories and moves images to the correct location.
- """
- logger.info("\nFixing directory structure...")
+ Clean up parser output directories after image migration.
- # Find nested content lists
- content_list_moves = []
- for doc_dir in self.content_list_dir.glob("*"):
- if not doc_dir.is_dir():
- continue
+ NOTE: Image migration and path updates are now handled by the RAG pipeline
+ (raganything.py / raganything_docling.py) BEFORE RAG insertion. This ensures
+ RAG stores the correct canonical image paths (kb/images/) from the start.
- auto_dir = doc_dir / "auto"
- if not auto_dir.exists():
- continue
+ This method now only:
+ 1. Checks if there are any leftover nested directories to clean up
+ 2. Removes empty temporary parser output directories
- # Find the _content_list.json file
- for json_file in auto_dir.glob("*_content_list.json"):
- target_file = self.content_list_dir / f"{doc_dir.name}.json"
- content_list_moves.append((json_file, target_file))
+ Supports both 'auto' (MinerU) and 'docling' parser output directories.
+ """
+ logger.info("\nChecking for leftover parser output directories...")
- # Move content list files
- for source, target in content_list_moves:
- try:
- shutil.copy2(source, target)
- logger.info(f" ✓ Moved: {source.name} -> {target.name}")
- except Exception as e:
- logger.error(f" ✗ Error moving {source.name}: {e!s}")
+ # Support both 'auto' (MinerU) and 'docling' parser output directories
+ parser_subdirs = ["auto", "docling"]
+ cleaned_count = 0
- # Find and move nested images
- for doc_dir in self.content_list_dir.glob("*"):
+ # Find and remove empty parser output directories
+ for doc_dir in list(self.content_list_dir.glob("*")):
if not doc_dir.is_dir():
continue
- auto_dir = doc_dir / "auto"
- if not auto_dir.exists():
- continue
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Check if directory is empty or only contains empty subdirs
+ has_content = any(
+ f.is_file() or (f.is_dir() and any(f.iterdir()))
+ for f in subdir.iterdir()
+ )
+
+ if not has_content:
+ shutil.rmtree(subdir)
+ cleaned_count += 1
+ logger.debug(f" Removed empty directory: {subdir}")
+ except Exception as e:
+ logger.debug(f" Could not clean up {subdir}: {e}")
+
+ # Remove doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ logger.debug(f" Removed empty directory: {doc_dir}")
+ except Exception:
+ pass
- images_dir = auto_dir / "images"
- if images_dir.exists() and images_dir.is_dir():
- image_count = 0
- # Ensure target directory exists
- self.images_dir.mkdir(parents=True, exist_ok=True)
-
- for img_file in images_dir.glob("*"):
- if img_file.is_file() and img_file.exists():
- target_img = self.images_dir / img_file.name
- if not target_img.exists():
- try:
- # Ensure source file exists
- if not img_file.exists():
- logger.warning(f" ⚠ Source image not found: {img_file}")
- continue
- shutil.copy2(img_file, target_img)
- image_count += 1
- except FileNotFoundError:
- logger.error(
- f" ✗ Error moving image {img_file.name}: Source file not found: {img_file}"
- )
- except Exception as e:
- logger.error(f" ✗ Error moving image {img_file.name}: {e!s}")
-
- if image_count > 0:
- logger.info(f" ✓ Moved {image_count} images from {doc_dir.name}/auto/images/")
-
- # Clean up nested directories
- for doc_dir in self.content_list_dir.glob("*"):
- if doc_dir.is_dir():
- try:
- shutil.rmtree(doc_dir)
- logger.info(f" ✓ Cleaned up: {doc_dir.name}/")
- except Exception as e:
- logger.error(f" ✗ Error removing {doc_dir.name}: {e!s}")
-
- logger.info("✓ Structure fixed!")
+ if cleaned_count > 0:
+ logger.info(f"✓ Cleaned up {cleaned_count} empty parser directories")
+ else:
+ logger.info("✓ No cleanup needed (structure already organized)")
def extract_numbered_items(self, batch_size: int = 20):
"""
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index ebba790da..32c04525c 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -413,7 +413,6 @@ 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 1ae905dac..fac531675 100644
--- a/src/logging/__init__.py
+++ b/src/logging/__init__.py
@@ -39,6 +39,7 @@ from .adapters import (
from .config import (
LoggingConfig,
get_default_log_dir,
+ get_global_log_level,
load_logging_config,
)
@@ -58,6 +59,7 @@ from .logger import (
LogLevel,
get_logger,
reset_logger,
+ set_default_service_prefix,
)
# Statistics tracking
@@ -75,6 +77,7 @@ __all__ = [
"LogLevel",
"get_logger",
"reset_logger",
+ "set_default_service_prefix",
"ConsoleFormatter",
"FileFormatter",
# Handlers
@@ -100,4 +103,5 @@ __all__ = [
"LoggingConfig",
"load_logging_config",
"get_default_log_dir",
+ "get_global_log_level",
]
diff --git a/src/logging/adapters/lightrag.py b/src/logging/adapters/lightrag.py
index 52adaff41..6e59c2dd3 100644
--- a/src/logging/adapters/lightrag.py
+++ b/src/logging/adapters/lightrag.py
@@ -4,6 +4,7 @@ LightRAG Log Forwarder
======================
Forwards LightRAG and RAG-Anything logs to DeepTutor's unified logging system.
+Uses the unified global log level from config/main.yaml -> logging.level
"""
from contextlib import contextmanager
@@ -31,17 +32,21 @@ class LightRAGLogForwarder(logging.Handler):
def emit(self, record: logging.LogRecord):
"""
- Forward log record to DeepTutor logger.
- All logs are forwarded as info level to maintain consistent format.
+ Forward log record to DeepTutor logger with proper level mapping.
"""
try:
- # Get the original message directly without adding [LightRAG] prefix
- # LightRAG already formats messages appropriately (e.g., "DEBUG: xxx" for debug logs)
message = record.getMessage()
- # Use info() for all levels to maintain consistent format
- # This ensures all logs appear as [RAGTool] ... (or [RAGTool] DEBUG: ... for debug)
- self.ai_tutor_logger.info(message)
+ # Map LightRAG log levels to DeepTutor logger methods
+ level = record.levelno
+ if level >= logging.ERROR:
+ self.ai_tutor_logger.error(message)
+ elif level >= logging.WARNING:
+ self.ai_tutor_logger.warning(message)
+ elif level >= logging.INFO:
+ self.ai_tutor_logger.info(message)
+ else:
+ self.ai_tutor_logger.debug(message)
except Exception:
# Avoid errors in forwarding from affecting main flow
@@ -50,35 +55,35 @@ class LightRAGLogForwarder(logging.Handler):
def get_lightrag_forwarding_config() -> dict:
"""
- Load LightRAG forwarding configuration from main.yaml.
+ Load LightRAG forwarding configuration from config/main.yaml.
Returns:
dict: Configuration dictionary with defaults if not found
"""
try:
+ from ..config import get_global_log_level
from src.services.config import load_config_with_main
- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
project_root = Path(__file__).resolve().parent.parent.parent.parent
config = load_config_with_main("solve_config.yaml", project_root)
+ logging_config = config.get("logging", {})
- forwarding_config = config.get("logging", {}).get("lightrag_forwarding", {})
+ # Use the unified global log level
+ level = get_global_log_level()
return {
- "enabled": forwarding_config.get("enabled", True),
- "min_level": forwarding_config.get("min_level", "INFO"),
- "add_prefix": forwarding_config.get("add_prefix", True),
- "logger_names": forwarding_config.get(
- "logger_names", {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"}
+ "enabled": True,
+ "min_level": level,
+ "logger_names": logging_config.get(
+ "rag_logger_names", {"knowledge_init": "RAG-Init", "rag_tool": "RAG"}
),
}
except Exception:
# Return defaults if config loading fails
return {
"enabled": True,
- "min_level": "INFO",
- "add_prefix": True,
- "logger_names": {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"},
+ "min_level": "DEBUG",
+ "logger_names": {"knowledge_init": "RAG-Init", "rag_tool": "RAG"},
}
diff --git a/src/logging/config.py b/src/logging/config.py
index e8d16f09e..f41ca2b51 100644
--- a/src/logging/config.py
+++ b/src/logging/config.py
@@ -2,42 +2,36 @@
Logging Configuration
=====================
-Configuration settings for the logging system.
+Unified logging configuration for the entire DeepTutor system.
+A single `level` parameter controls all logging (including RAG modules).
"""
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional
+from typing import Dict, Optional
@dataclass
class LoggingConfig:
"""Configuration for the logging system."""
+ # Global log level (controls entire system including RAG modules)
+ level: str = "DEBUG"
+
# Output settings
console_output: bool = True
file_output: bool = True
- # Log levels
- console_level: str = "INFO"
- file_level: str = "DEBUG"
-
# Log directory (relative to project root or absolute)
log_dir: Optional[str] = None
+ # RAG module logger name mapping
+ rag_logger_names: Optional[Dict[str, str]] = None
+
# File rotation settings
max_bytes: int = 10 * 1024 * 1024 # 10MB
backup_count: int = 5
- # WebSocket streaming
- websocket_enabled: bool = True
- websocket_queue_size: int = 1000
-
- # LightRAG forwarding
- lightrag_forwarding_enabled: bool = True
- lightrag_min_level: str = "INFO"
- lightrag_add_prefix: bool = True
-
def get_default_log_dir() -> Path:
"""Get the default log directory."""
@@ -45,6 +39,22 @@ def get_default_log_dir() -> Path:
return project_root / "data" / "user" / "logs"
+def get_global_log_level() -> str:
+ """
+ Get the global log level from config/main.yaml -> logging.level
+ Default: DEBUG
+ """
+ try:
+ from src.services.config import load_config_with_main
+
+ project_root = Path(__file__).resolve().parent.parent.parent
+ config = load_config_with_main("solve_config.yaml", project_root)
+ logging_config = config.get("logging", {})
+ return logging_config.get("level", "DEBUG").upper()
+ except Exception:
+ return "DEBUG"
+
+
def load_logging_config() -> LoggingConfig:
"""
Load logging configuration from config files.
@@ -59,22 +69,14 @@ def load_logging_config() -> LoggingConfig:
config = load_config_with_main("solve_config.yaml", project_root)
logging_config = config.get("logging", {})
+ level = get_global_log_level()
return LoggingConfig(
+ level=level,
console_output=logging_config.get("console_output", True),
- file_output=logging_config.get("file_output", True),
- console_level=logging_config.get("console_level", "INFO"),
- file_level=logging_config.get("file_level", "DEBUG"),
+ file_output=logging_config.get("save_to_file", True),
log_dir=get_path_from_config(config, "user_log_dir"),
- lightrag_forwarding_enabled=logging_config.get("lightrag_forwarding", {}).get(
- "enabled", True
- ),
- lightrag_min_level=logging_config.get("lightrag_forwarding", {}).get(
- "min_level", "INFO"
- ),
- lightrag_add_prefix=logging_config.get("lightrag_forwarding", {}).get(
- "add_prefix", True
- ),
+ rag_logger_names=logging_config.get("rag_logger_names"),
)
except Exception:
return LoggingConfig()
diff --git a/src/logging/handlers/console.py b/src/logging/handlers/console.py
index ea4f3d99a..521cb867d 100644
--- a/src/logging/handlers/console.py
+++ b/src/logging/handlers/console.py
@@ -3,59 +3,15 @@
Console Log Handler
===================
-Color-coded console output with symbols.
+Color-coded console output with standard level tags.
"""
import logging
import sys
+from typing import Optional
-
-class ConsoleFormatter(logging.Formatter):
- """
- Clean console formatter with colors and symbols.
- Format: [Module] Symbol Message
- """
-
- # ANSI color codes
- COLORS = {
- "DEBUG": "\033[90m", # Gray
- "INFO": "\033[37m", # White
- "SUCCESS": "\033[32m", # Green
- "WARNING": "\033[33m", # Yellow
- "ERROR": "\033[31m", # Red
- "CRITICAL": "\033[35m", # Magenta
- }
- RESET = "\033[0m"
- BOLD = "\033[1m"
- DIM = "\033[2m"
-
- # Symbols for different log types
- SYMBOLS = {
- "DEBUG": "·",
- "INFO": "●",
- "SUCCESS": "✓",
- "WARNING": "⚠",
- "ERROR": "✗",
- "CRITICAL": "✗",
- }
-
- def format(self, record: logging.LogRecord) -> str:
- # Get module name (padded to 12 chars for alignment)
- module = getattr(record, "module_name", record.name)
- module_padded = f"[{module}]".ljust(14)
-
- # Get symbol (can be overridden via record.symbol)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))
-
- # Get color
- level = getattr(record, "display_level", record.levelname)
- color = self.COLORS.get(level, self.COLORS["INFO"])
-
- # Format message
- message = record.getMessage()
-
- # Build output: [Module] ● Message
- return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"
+# Import ConsoleFormatter from the main logger module to avoid duplication
+from ..logger import ConsoleFormatter
class ConsoleHandler(logging.StreamHandler):
@@ -63,13 +19,14 @@ class ConsoleHandler(logging.StreamHandler):
Console handler with color-coded output.
"""
- def __init__(self, level: int = logging.INFO):
+ def __init__(self, level: int = logging.INFO, service_prefix: Optional[str] = None):
"""
Initialize console handler.
Args:
level: Minimum log level to display
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
"""
super().__init__(sys.stdout)
self.setLevel(level)
- self.setFormatter(ConsoleFormatter())
+ self.setFormatter(ConsoleFormatter(service_prefix=service_prefix))
diff --git a/src/logging/handlers/file.py b/src/logging/handlers/file.py
index 7ae3dce3a..c7985d3bc 100644
--- a/src/logging/handlers/file.py
+++ b/src/logging/handlers/file.py
@@ -13,24 +13,8 @@ from logging.handlers import RotatingFileHandler as BaseRotatingFileHandler
from pathlib import Path
from typing import Optional
-
-class FileFormatter(logging.Formatter):
- """
- Detailed file formatter for log files.
- Format: TIMESTAMP [LEVEL] [Module] Message
- """
-
- def __init__(self):
- super().__init__(
- fmt="%(asctime)s [%(levelname)-8s] [%(module_name)-12s] %(message)s",
- datefmt="%Y-%m-%d %H:%M:%S",
- )
-
- def format(self, record: logging.LogRecord) -> str:
- # Ensure module_name exists
- if not hasattr(record, "module_name"):
- record.module_name = record.name
- return super().format(record)
+# Import FileFormatter from the main logger module to avoid duplication
+from ..logger import FileFormatter
class FileHandler(logging.FileHandler):
@@ -143,7 +127,7 @@ class JSONFileHandler(logging.Handler):
}
# Add extra fields if present
- for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
+ for key in ["display_level", "tool_name", "elapsed_ms", "tokens"]:
if hasattr(record, key):
entry[key] = getattr(record, key)
@@ -180,7 +164,7 @@ def create_task_logger(
log_path.mkdir(parents=True, exist_ok=True)
# Create logger
- logger = logging.getLogger(f"ai_tutor.{module_name}.{task_id}")
+ logger = logging.getLogger(f"deeptutor.{module_name}.{task_id}")
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
logger.propagate = False
diff --git a/src/logging/handlers/websocket.py b/src/logging/handlers/websocket.py
index 92c0c3b35..754339ad3 100644
--- a/src/logging/handlers/websocket.py
+++ b/src/logging/handlers/websocket.py
@@ -8,6 +8,7 @@ Handlers for streaming logs to WebSocket clients.
import asyncio
import logging
+from typing import Optional
class WebSocketLogHandler(logging.Handler):
@@ -25,27 +26,24 @@ class WebSocketLogHandler(logging.Handler):
await websocket.send_json(log_entry)
"""
- # Symbols for different log types (matching ConsoleFormatter)
- SYMBOLS = {
- "DEBUG": "·",
- "INFO": "●",
- "SUCCESS": "✓",
- "WARNING": "⚠",
- "ERROR": "✗",
- "CRITICAL": "✗",
- }
-
- def __init__(self, queue: asyncio.Queue, include_module: bool = True):
+ def __init__(
+ self,
+ queue: asyncio.Queue,
+ include_module: bool = True,
+ service_prefix: Optional[str] = None,
+ ):
"""
Initialize WebSocket log handler.
Args:
queue: asyncio.Queue to put log entries into
include_module: Whether to include module name in output
+ service_prefix: Optional service layer prefix (e.g., "Backend")
"""
super().__init__()
self.queue = queue
self.include_module = include_module
+ self.service_prefix = service_prefix
self.setFormatter(logging.Formatter("%(message)s"))
def emit(self, record: logging.LogRecord):
@@ -53,25 +51,31 @@ class WebSocketLogHandler(logging.Handler):
try:
msg = self.format(record)
- # Get symbol
+ # Get display level
display_level = getattr(record, "display_level", record.levelname)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(display_level, "●"))
# Get module name
module_name = getattr(record, "module_name", record.name)
- # Build formatted content
- if self.include_module:
- content = f"[{module_name}] {symbol} {msg}"
+ # Build formatted content with standard level tags (compact format)
+ level_tag = display_level
+ if self.service_prefix:
+ service_tag = f"[{self.service_prefix}]"
+ if self.include_module:
+ content = f"{service_tag} {level_tag} [{module_name}] {msg}"
+ else:
+ content = f"{service_tag} {level_tag} {msg}"
else:
- content = f"{symbol} {msg}"
+ if self.include_module:
+ content = f"{level_tag} [{module_name}] {msg}"
+ else:
+ content = f"{level_tag} {msg}"
# Construct structured message
log_entry = {
"type": "log",
"level": display_level,
"module": module_name,
- "symbol": symbol,
"content": content,
"message": msg,
"timestamp": record.created,
@@ -93,7 +97,7 @@ class LogInterceptor:
Usage:
queue = asyncio.Queue()
- logger = logging.getLogger("ai_tutor.Solver")
+ logger = logging.getLogger("deeptutor.Solver")
with LogInterceptor(logger, queue):
# All logs from this logger will be streamed to queue
diff --git a/src/logging/logger.py b/src/logging/logger.py
index 78640595c..f1b0787f7 100644
--- a/src/logging/logger.py
+++ b/src/logging/logger.py
@@ -4,13 +4,14 @@ Core Logger Implementation
==========================
Unified logging with consistent format across all modules.
-Format: [Module] Symbol Message
+Format: [LEVEL] [Module] Message
Example outputs:
- [Solver] ✓ Ready in 2.3s
- [Research] → Starting deep research...
- [Guide] → Compiling knowledge points
- [Knowledge] ✓ Indexed 150 documents
+ [INFO] [Solver] Ready in 2.3s
+ [INFO] [Research] Starting deep research...
+ [INFO] [Guide] Compiling knowledge points
+ [INFO] [Knowledge] Indexed 150 documents
+ [ERROR] [EmbeddingClient] Embedding request failed
"""
from datetime import datetime
@@ -21,26 +22,26 @@ from pathlib import Path
import sys
from typing import Any, List, Optional, Union
-from src.config.constants import LOG_SYMBOLS, PROJECT_ROOT
+from src.config.constants import PROJECT_ROOT
class LogLevel(Enum):
- """Log levels with associated symbols"""
+ """Log levels with standard tags"""
- DEBUG = ("DEBUG", "·") # Dot for debug
- INFO = ("INFO", "●") # Circle for info
- SUCCESS = ("SUCCESS", "✓") # Checkmark for success
- WARNING = ("WARNING", "⚠") # Warning sign
- ERROR = ("ERROR", "✗") # X for error
- CRITICAL = ("CRITICAL", "✗") # X for critical
- PROGRESS = ("INFO", "→") # Arrow for progress
- COMPLETE = ("INFO", "✓") # Checkmark for completion
+ DEBUG = "DEBUG"
+ INFO = "INFO"
+ SUCCESS = "SUCCESS"
+ WARNING = "WARNING"
+ ERROR = "ERROR"
+ CRITICAL = "CRITICAL"
+ PROGRESS = "PROGRESS"
+ COMPLETE = "COMPLETE"
class ConsoleFormatter(logging.Formatter):
"""
- Clean console formatter with colors and symbols.
- Format: [Module] Symbol Message
+ Clean console formatter with colors and standard level tags.
+ Format: [LEVEL] [Module] Message
"""
# ANSI color codes
@@ -51,36 +52,46 @@ class ConsoleFormatter(logging.Formatter):
"WARNING": "\033[33m", # Yellow
"ERROR": "\033[31m", # Red
"CRITICAL": "\033[35m", # Magenta
+ "PROGRESS": "\033[36m", # Cyan
+ "COMPLETE": "\033[32m", # Green
}
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
- # Symbols for different log types
- SYMBOLS = LOG_SYMBOLS
+ def __init__(self, service_prefix: Optional[str] = None):
+ """
+ Initialize console formatter.
- def __init__(self):
+ Args:
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
+ """
super().__init__()
+ self.service_prefix = service_prefix
# Check TTY status once during initialization
stdout_tty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
stderr_tty = hasattr(sys.stderr, "isatty") and sys.stderr.isatty()
self.use_colors = stdout_tty or stderr_tty
def format(self, record: logging.LogRecord) -> str:
- # Get module name (padded to 12 chars for alignment)
+ # Get display level (may be custom like SUCCESS, PROGRESS)
+ display_level = getattr(record, "display_level", record.levelname)
+
+ # Get module name
module = getattr(record, "module_name", record.name)
- module_padded = f"[{module}]".ljust(14)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))
+
+ # Build module tag [Module]
+ module_tag = f"[{module}]"
+
+ # Build level tag with colon
+ level_tag = f"{display_level}:"
+
# Use pre-computed TTY status
- use_colors = self.use_colors
- if use_colors:
- # Get color
- level = getattr(record, "display_level", record.levelname)
- color = self.COLORS.get(level, self.COLORS["INFO"])
+ if self.use_colors:
+ color = self.COLORS.get(display_level, self.COLORS["INFO"])
dim = self.DIM
reset = self.RESET
else:
- # No colors for non-interactive output
color = ""
dim = ""
reset = ""
@@ -88,8 +99,12 @@ class ConsoleFormatter(logging.Formatter):
# Format message
message = record.getMessage()
- # Build output: [Module] ● Message
- return f"{dim}{module_padded}{reset} {color}{symbol}{reset} {message}"
+ # Build output: [Backend] [Module] INFO: Message (module first, then level)
+ if self.service_prefix:
+ service_tag = f"[{self.service_prefix}]"
+ return f"{dim}{service_tag}{reset} {dim}{module_tag}{reset} {color}{level_tag}{reset} {message}"
+ else:
+ return f"{dim}{module_tag}{reset} {color}{level_tag}{reset} {message}"
class FileFormatter(logging.Formatter):
@@ -121,6 +136,7 @@ class Logger:
- File logging to user/logs/
- WebSocket streaming support
- Success/progress/complete convenience methods
+ - Optional service layer prefix (Backend/Frontend)
Usage:
logger = Logger("Solver")
@@ -136,6 +152,7 @@ class Logger:
console_output: bool = True,
file_output: bool = True,
log_dir: Optional[Union[str, Path]] = None,
+ service_prefix: Optional[str] = None,
):
"""
Initialize logger.
@@ -146,14 +163,17 @@ class Logger:
console_output: Whether to output to console
file_output: Whether to output to file
log_dir: Log directory (default: ../user/logs/)
+ service_prefix: Optional service layer prefix (e.g., "Backend", "Frontend")
"""
self.name = name
self.level = getattr(logging, level.upper(), logging.INFO)
+ self.service_prefix = service_prefix
# Create underlying Python logger
- self.logger = logging.getLogger(f"ai_tutor.{name}")
+ self.logger = logging.getLogger(f"deeptutor.{name}")
self.logger.setLevel(logging.DEBUG) # Capture all, filter at handlers
self.logger.handlers.clear()
+ self.logger.propagate = False # Prevent duplicate logs from root logger
# Setup log directory
log_dir_path: Path
if log_dir is None:
@@ -171,13 +191,13 @@ class Logger:
if console_output:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(self.level)
- console_handler.setFormatter(ConsoleFormatter())
+ console_handler.setFormatter(ConsoleFormatter(service_prefix=service_prefix))
self.logger.addHandler(console_handler)
# File handler
if file_output:
timestamp = datetime.now().strftime("%Y%m%d")
- log_file = log_dir_path / f"ai_tutor_{timestamp}.log"
+ log_file = log_dir_path / f"deeptutor_{timestamp}.log"
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG) # Log everything to file
@@ -234,14 +254,12 @@ class Logger:
self,
level: int,
message: str,
- symbol: Optional[str] = None,
display_level: Optional[str] = None,
**kwargs,
):
"""Internal logging method with extra attributes."""
extra = {
"module_name": self.name,
- "symbol": symbol,
"display_level": display_level or logging.getLevelName(level),
}
# Extract standard logging parameters from kwargs
@@ -255,45 +273,43 @@ class Logger:
# Standard logging methods
def debug(self, message: str, **kwargs):
- """Debug level log (·)"""
- self._log(logging.DEBUG, message, symbol="·", **kwargs)
+ """Debug level log [DEBUG]"""
+ self._log(logging.DEBUG, message, **kwargs)
def info(self, message: str, **kwargs):
- """Info level log (●)"""
- self._log(logging.INFO, message, symbol="●", **kwargs)
+ """Info level log [INFO]"""
+ self._log(logging.INFO, message, **kwargs)
def warning(self, message: str, **kwargs):
- """Warning level log (⚠)"""
- self._log(logging.WARNING, message, symbol="⚠", **kwargs)
+ """Warning level log [WARNING]"""
+ self._log(logging.WARNING, message, **kwargs)
def error(self, message: str, **kwargs):
- """Error level log (✗)"""
- self._log(logging.ERROR, message, symbol="✗", **kwargs)
+ """Error level log [ERROR]"""
+ self._log(logging.ERROR, message, **kwargs)
def critical(self, message: str, **kwargs):
- """Critical level log (✗)"""
- self._log(logging.CRITICAL, message, symbol="✗", **kwargs)
+ """Critical level log [CRITICAL]"""
+ self._log(logging.CRITICAL, message, **kwargs)
def exception(self, message: str, **kwargs):
"""Log exception with traceback"""
- self.logger.exception(
- message, extra={"module_name": self.name, "symbol": "✗", "display_level": "ERROR"}
- )
+ self.logger.exception(message, extra={"module_name": self.name, "display_level": "ERROR"})
# Convenience methods
def success(self, message: str, elapsed: Optional[float] = None, **kwargs):
- """Success log with checkmark (✓)"""
+ """Success log [SUCCESS]"""
if elapsed is not None:
message = f"{message} in {elapsed:.1f}s"
- self._log(logging.INFO, message, symbol="✓", display_level="SUCCESS", **kwargs)
+ self._log(logging.INFO, message, display_level="SUCCESS", **kwargs)
def progress(self, message: str, **kwargs):
- """Progress log with arrow (→)"""
- self._log(logging.INFO, message, symbol="→", **kwargs)
+ """Progress log [PROGRESS]"""
+ self._log(logging.INFO, message, display_level="PROGRESS", **kwargs)
def complete(self, message: str, **kwargs):
- """Completion log with checkmark (✓)"""
- self._log(logging.INFO, message, symbol="✓", display_level="SUCCESS", **kwargs)
+ """Completion log [COMPLETE]"""
+ self._log(logging.INFO, message, display_level="COMPLETE", **kwargs)
def stage(self, stage_name: str, status: str = "start", detail: Optional[str] = None):
"""
@@ -304,15 +320,16 @@ class Logger:
status: One of "start", "running", "complete", "skip", "error"
detail: Optional detail message
"""
- symbols = {
- "start": "▶",
- "running": "●",
- "complete": "✓",
- "skip": "○",
- "error": "✗",
- "warning": "⚠",
+ # Map status to display level
+ status_to_level = {
+ "start": "PROGRESS",
+ "running": "INFO",
+ "complete": "SUCCESS",
+ "skip": "INFO",
+ "error": "ERROR",
+ "warning": "WARNING",
}
- symbol = symbols.get(status, "●")
+ display_level = status_to_level.get(status, "INFO")
message = f"{stage_name}"
if status == "complete":
@@ -330,10 +347,7 @@ class Logger:
message += f" | {detail}"
level = logging.ERROR if status == "error" else logging.INFO
- display_level = (
- "ERROR" if status == "error" else ("SUCCESS" if status == "complete" else "INFO")
- )
- self._log(level, message, symbol=symbol, display_level=display_level)
+ self._log(level, message, display_level=display_level)
def tool_call(
self, tool_name: str, status: str = "success", elapsed_ms: Optional[float] = None, **kwargs
@@ -346,7 +360,6 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "✓" if status == "success" else ("✗" if status == "error" else "●")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -360,7 +373,6 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
- symbol=symbol,
display_level=display_level,
)
@@ -394,7 +406,7 @@ class Logger:
parts.append(f"{elapsed:.2f}s")
message = " | ".join(parts)
- self._log(logging.DEBUG, message, symbol="◆")
+ self._log(logging.DEBUG, message)
def separator(self, char: str = "─", length: int = 50):
"""Print a separator line"""
@@ -420,7 +432,6 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "✓" if status == "success" else ("✗" if status == "error" else "●")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -435,7 +446,6 @@ class Logger:
self._log(
logging.INFO if status != "error" else logging.ERROR,
message,
- symbol=symbol,
display_level=display_level,
)
@@ -509,22 +519,20 @@ class Logger:
level: Log level ("DEBUG" for full details, "INFO" for summary)
"""
# Build header
- header_parts = ["[LLM-CALL]"]
+ header_parts = ["LLM-CALL"]
if agent_name:
- header_parts.append(f"[Agent: {agent_name}]")
- header_parts.append(f"[Stage: {stage}]")
- header_parts.append(f"[Model: {model}]")
- header = " ".join(header_parts)
+ header_parts.append(f"Agent: {agent_name}")
+ header_parts.append(f"Stage: {stage}")
+ header_parts.append(f"Model: {model}")
+ header = " | ".join(header_parts)
# Log at appropriate level
log_level = logging.DEBUG if level == "DEBUG" else logging.INFO
if level == "DEBUG":
# Full detailed output
- self._log(log_level, header, symbol="◆")
- self._log(
- log_level, "┌─ Input ──────────────────────────────────────────────", symbol=" "
- )
+ self._log(log_level, header)
+ self._log(log_level, "--- Input ---")
self._log(
log_level,
(
@@ -532,7 +540,6 @@ class Logger:
if len(system_prompt) > 200
else f"System: {system_prompt}"
),
- symbol=" ",
)
self._log(
log_level,
@@ -541,20 +548,9 @@ class Logger:
if len(user_prompt) > 500
else f"User: {user_prompt}"
),
- symbol=" ",
- )
- self._log(
- log_level, "└──────────────────────────────────────────────────────", symbol=" "
- )
- self._log(
- log_level, "┌─ Output ─────────────────────────────────────────────", symbol=" "
- )
- self._log(
- log_level, f"{response[:1000]}..." if len(response) > 1000 else response, symbol=" "
- )
- self._log(
- log_level, "└──────────────────────────────────────────────────────", symbol=" "
)
+ self._log(log_level, "--- Output ---")
+ self._log(log_level, f"{response[:1000]}..." if len(response) > 1000 else response)
# Token and cost info
token_info_parts = []
@@ -568,17 +564,17 @@ class Logger:
token_info_parts.append(f"cost=${cost:.6f}")
if token_info_parts:
- self._log(log_level, f"[Tokens: {' '.join(token_info_parts)}]", symbol=" ")
+ self._log(log_level, f"Tokens: {' '.join(token_info_parts)}")
else:
# Summary output
token_info = ""
if input_tokens is not None and output_tokens is not None:
- token_info = f" [Tokens: in={input_tokens}, out={output_tokens}, total={input_tokens + output_tokens}]"
+ token_info = f" | Tokens: in={input_tokens}, out={output_tokens}, total={input_tokens + output_tokens}"
if cost is not None:
- token_info += f" [Cost: ${cost:.6f}]"
+ token_info += f" | Cost: ${cost:.6f}"
message = f"{header}{token_info}"
- self._log(log_level, message, symbol="◆")
+ self._log(log_level, message)
def update_token_stats(self, summary: dict[str, Any]):
"""Update token statistics (for display manager compatibility)"""
@@ -609,67 +605,99 @@ class Logger:
self.logger.removeHandler(handler)
-# Global logger registry - key is tuple of (name, level, console_output, file_output, log_dir)
-_loggers: dict[tuple[str, str, bool, bool, Optional[str]], "Logger"] = {}
+# Global logger registry - key is tuple of (name, level, console_output, file_output, log_dir, service_prefix)
+_loggers: dict[tuple[str, str, bool, bool, Optional[str], Optional[str]], "Logger"] = {}
+
+# Global default service prefix (can be set at application startup)
+_default_service_prefix: Optional[str] = None
+
+
+def set_default_service_prefix(prefix: Optional[str]):
+ """
+ Set the default service prefix for all new loggers.
+
+ Call this at application startup to set a global prefix like "Backend" or "Frontend".
+
+ Args:
+ prefix: Service prefix (e.g., "Backend", "Frontend") or None to disable
+ """
+ global _default_service_prefix
+ _default_service_prefix = prefix
def get_logger(
name: str = "Main",
- level: str = "INFO",
+ level: Optional[str] = None,
console_output: bool = True,
file_output: bool = True,
log_dir: Optional[str] = None,
+ service_prefix: Optional[str] = None,
) -> Logger:
"""
Get or create a logger instance.
Args:
name: Module name
- level: Log level
+ level: Log level (if None, uses global level from config/main.yaml)
console_output: Enable console output
file_output: Enable file output
log_dir: Log directory (if None, will try to load from config/main.yaml)
+ service_prefix: Optional service prefix (if None, uses default set by set_default_service_prefix)
Returns:
Logger instance
"""
- global _loggers
+ global _loggers, _default_service_prefix
- # If log_dir not provided, try to load from config
- if log_dir is None:
+ # Use default service prefix if not explicitly provided
+ effective_service_prefix = (
+ service_prefix if service_prefix is not None else _default_service_prefix
+ )
+
+ # Load config for log_dir and level
+ effective_level = level
+ if log_dir is None or effective_level is None:
try:
from src.services.config import get_path_from_config, load_config_with_main
- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
- config = load_config_with_main(
- "solve_config.yaml", PROJECT_ROOT
- ) # Use any config to get main.yaml
- log_dir = get_path_from_config(config, "user_log_dir") or config.get("paths", {}).get(
- "user_log_dir"
- )
- if log_dir:
- # Convert relative path to absolute based on project root
- log_dir_path = Path(log_dir)
- if not log_dir_path.is_absolute():
- # Remove leading ./ if present
- log_dir_str = str(log_dir_path).lstrip("./")
- log_dir = str(PROJECT_ROOT / log_dir_str)
- else:
- log_dir = str(log_dir_path)
+ config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)
+
+ # Get log_dir from config
+ if log_dir is None:
+ log_dir = get_path_from_config(config, "user_log_dir") or config.get(
+ "paths", {}
+ ).get("user_log_dir")
+ if log_dir:
+ log_dir_path = Path(log_dir)
+ if not log_dir_path.is_absolute():
+ log_dir_str = str(log_dir_path).lstrip("./")
+ log_dir = str(PROJECT_ROOT / log_dir_str)
+ else:
+ log_dir = str(log_dir_path)
+
+ # Get level from config (unified global level)
+ if effective_level is None:
+ from .config import get_global_log_level
+
+ effective_level = get_global_log_level()
except Exception:
- # Fallback to default
pass
+
+ # Use DEBUG as ultimate fallback
+ if effective_level is None:
+ effective_level = "DEBUG"
+
log_dir_key = str(log_dir) if log_dir is not None else None
- # Create a cache key that includes configuration, using a normalized log_dir
- cache_key = (name, level, console_output, file_output, log_dir_key)
+ cache_key = (name, effective_level, console_output, file_output, log_dir_key, effective_service_prefix)
if cache_key not in _loggers:
_loggers[cache_key] = Logger(
name=name,
- level=level,
+ level=effective_level,
console_output=console_output,
file_output=file_output,
log_dir=log_dir,
+ service_prefix=effective_service_prefix,
)
return _loggers[cache_key]
diff --git a/src/logging/stats/llm_stats.py b/src/logging/stats/llm_stats.py
index 8070240e1..a5552b8b6 100644
--- a/src/logging/stats/llm_stats.py
+++ b/src/logging/stats/llm_stats.py
@@ -4,12 +4,12 @@ LLM Stats Tracker
=================
Simple utility for tracking LLM token usage and costs across all modules.
-Outputs summary to terminal at the end of processing.
+Outputs summary via the unified logging system.
Usage:
from src.logging import LLMStats
- stats = LLMStats()
+ stats = LLMStats("Solver")
# After each LLM call:
stats.add_call(
@@ -19,12 +19,15 @@ Usage:
)
# At the end:
- stats.print_summary()
+ stats.log_summary() # Uses logging system
"""
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:
+ from ..logger import Logger
# Model pricing per 1K tokens (USD)
MODEL_PRICING = {
@@ -150,25 +153,42 @@ class LLMStats:
"cost_usd": self.total_cost,
}
- def print_summary(self):
- """Print summary to terminal."""
+ def log_summary(self, logger: Optional["Logger"] = None):
+ """
+ Log summary using the unified logging system.
+
+ Args:
+ logger: Optional Logger instance. If None, creates one using module_name.
+ """
if len(self.calls) == 0:
return
+ # Import here to avoid circular imports
+ from ..logger import get_logger
+
+ if logger is None:
+ logger = get_logger(self.module_name)
+
total_tokens = self.total_prompt_tokens + self.total_completion_tokens
- print()
- print("=" * 60)
- print(f"📊 [{self.module_name}] LLM Usage Summary")
- print("=" * 60)
- print(f" Model : {self.model_used or 'Unknown'}")
- print(f" API Calls : {len(self.calls)}")
- print(
- f" Tokens : {total_tokens:,} (Input: {self.total_prompt_tokens:,}, Output: {self.total_completion_tokens:,})"
+ logger.info("=" * 60)
+ logger.info(f"LLM Usage Summary for {self.module_name}")
+ logger.info("=" * 60)
+ logger.info(f"Model : {self.model_used or 'Unknown'}")
+ logger.info(f"API Calls : {len(self.calls)}")
+ logger.info(
+ f"Tokens : {total_tokens:,} (Input: {self.total_prompt_tokens:,}, Output: {self.total_completion_tokens:,})"
)
- print(f" Cost : ${self.total_cost:.6f} USD")
- print("=" * 60)
- print()
+ logger.info(f"Cost : ${self.total_cost:.6f} USD")
+ logger.info("=" * 60)
+
+ def print_summary(self):
+ """
+ Print summary to terminal.
+
+ Deprecated: Use log_summary() instead for consistent logging.
+ """
+ self.log_summary()
def reset(self):
"""Reset all statistics."""
diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.py
index f33f23972..44e2f23cb 100644
--- a/src/services/config/unified_config.py
+++ b/src/services/config/unified_config.py
@@ -537,7 +537,52 @@ class UnifiedConfigManager:
return False
data["active_id"] = config_id
- return self._save_configs(config_type, data)
+ success = self._save_configs(config_type, data)
+
+ # Update environment variables for LightRAG compatibility when LLM config changes
+ if success and config_type == ConfigType.LLM:
+ self._update_openai_env_vars_for_lightrag()
+
+ return success
+
+ def _update_openai_env_vars_for_lightrag(self):
+ """
+ Update OPENAI_API_KEY and OPENAI_BASE_URL environment variables for LightRAG.
+
+ LightRAG's internal functions read directly from os.environ["OPENAI_API_KEY"]
+ instead of using passed parameters. This method ensures the environment
+ variables are updated when the active LLM configuration changes.
+ """
+ try:
+ config = self.get_active_config(ConfigType.LLM)
+ if not config:
+ return
+
+ provider = config.get("provider", "openai")
+ api_key = config.get("api_key", "")
+ base_url = config.get("base_url", "")
+
+ # Only set env vars for OpenAI-compatible providers
+ if provider in ("openai", "azure_openai", "gemini", "deepseek"):
+ if api_key:
+ os.environ["OPENAI_API_KEY"] = api_key
+ logger.debug("Updated OPENAI_API_KEY env var for LightRAG compatibility")
+
+ if base_url:
+ os.environ["OPENAI_BASE_URL"] = base_url
+ logger.debug(f"Updated OPENAI_BASE_URL env var to {base_url}")
+
+ # Reset LLM client singleton to pick up new configuration
+ try:
+ from src.services.llm import reset_llm_client
+
+ reset_llm_client()
+ logger.debug("Reset LLM client singleton after config change")
+ except ImportError:
+ pass
+
+ except Exception as e:
+ logger.warning(f"Failed to update OpenAI env vars: {e}")
def get_env_status(self, config_type: ConfigType) -> Dict[str, bool]:
"""Check which environment variables are configured for a service type."""
diff --git a/src/services/llm/client.py b/src/services/llm/client.py
index f2105600f..941dd1541 100644
--- a/src/services/llm/client.py
+++ b/src/services/llm/client.py
@@ -31,9 +31,38 @@ class LLMClient:
Args:
config: LLM configuration. If None, loads from environment.
"""
+
self.config = config or get_llm_config()
self.logger = get_logger("LLMClient")
+ # Set environment variables for LightRAG compatibility
+ # LightRAG's internal functions (openai_complete_if_cache, etc.) read from
+ # os.environ["OPENAI_API_KEY"] even when api_key is passed as parameter.
+ # We must set these env vars early to ensure all LightRAG operations work.
+ self._setup_openai_env_vars()
+
+ def _setup_openai_env_vars(self):
+ """
+ Set OpenAI environment variables for LightRAG compatibility.
+
+ LightRAG's internal functions read from os.environ["OPENAI_API_KEY"]
+ even when api_key is passed as parameter. This method ensures the
+ environment variables are set for all LightRAG operations.
+ """
+ import os
+
+ binding = getattr(self.config, "binding", "openai")
+
+ # Only set env vars for OpenAI-compatible bindings
+ if binding in ("openai", "azure_openai", "gemini"):
+ if self.config.api_key:
+ os.environ["OPENAI_API_KEY"] = self.config.api_key
+ self.logger.debug("Set OPENAI_API_KEY env var for LightRAG compatibility")
+
+ if self.config.base_url:
+ os.environ["OPENAI_BASE_URL"] = self.config.base_url
+ self.logger.debug(f"Set OPENAI_BASE_URL env var to {self.config.base_url}")
+
async def complete(
self,
prompt: str,
@@ -128,6 +157,7 @@ class LLMClient:
return llm_model_func_via_factory
# OpenAI-compatible bindings use lightrag (has caching)
+ # Note: Environment variables are already set in __init__ via _setup_openai_env_vars()
from lightrag.llm.openai import openai_complete_if_cache
def llm_model_func(
@@ -196,6 +226,7 @@ class LLMClient:
return vision_model_func_via_factory
# OpenAI-compatible bindings
+ # Note: Environment variables are already set in __init__ via _setup_openai_env_vars()
from lightrag.llm.openai import openai_complete_if_cache
# Get api_version once for reuse
diff --git a/src/services/llm/config.py b/src/services/llm/config.py
index e071cc6a7..c11ba6650 100644
--- a/src/services/llm/config.py
+++ b/src/services/llm/config.py
@@ -26,6 +26,37 @@ load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
load_dotenv(PROJECT_ROOT / ".env", override=False)
+def _setup_openai_env_vars_early():
+ """
+ Set OPENAI_API_KEY environment variable early for LightRAG compatibility.
+
+ LightRAG's internal functions (e.g., create_openai_async_client) read directly
+ from os.environ["OPENAI_API_KEY"] instead of using the api_key parameter.
+ This function ensures the environment variable is set as soon as this module
+ is imported, before any LightRAG operations can occur.
+
+ This is called at module load time to ensure env vars are set before any
+ RAG operations, including those in worker threads/processes.
+ """
+ binding = os.getenv("LLM_BINDING", "openai")
+ api_key = os.getenv("LLM_API_KEY")
+ base_url = os.getenv("LLM_HOST")
+
+ # Only set env vars for OpenAI-compatible bindings
+ if binding in ("openai", "azure_openai", "gemini"):
+ if api_key and not os.getenv("OPENAI_API_KEY"):
+ os.environ["OPENAI_API_KEY"] = api_key
+ logger.debug("Set OPENAI_API_KEY env var for LightRAG compatibility (early init)")
+
+ if base_url and not os.getenv("OPENAI_BASE_URL"):
+ os.environ["OPENAI_BASE_URL"] = base_url
+ logger.debug(f"Set OPENAI_BASE_URL env var to {base_url} (early init)")
+
+
+# Execute early setup at module import time
+_setup_openai_env_vars_early()
+
+
@dataclass
class LLMConfig:
"""LLM configuration dataclass."""
diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.py
index fc8467eaa..9c56bc5dc 100644
--- a/src/services/rag/components/indexers/graph.py
+++ b/src/services/rag/components/indexers/graph.py
@@ -51,58 +51,18 @@ class GraphIndexer(BaseComponent):
sys.path.insert(0, str(raganything_path))
try:
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
diff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.py
index 63da12298..2a87a505e 100644
--- a/src/services/rag/components/indexers/lightrag.py
+++ b/src/services/rag/components/indexers/lightrag.py
@@ -53,57 +53,17 @@ class LightRAGIndexer(BaseComponent):
try:
from lightrag import LightRAG
- from openai import AsyncOpenAI
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
# Create pure LightRAG instance (no multimodal)
rag = LightRAG(
diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.py
index a594cb32b..8c1e3137f 100644
--- a/src/services/rag/components/retrievers/hybrid.py
+++ b/src/services/rag/components/retrievers/hybrid.py
@@ -50,58 +50,18 @@ class HybridRetriever(BaseComponent):
sys.path.insert(0, str(raganything_path))
try:
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.py
index c945a3617..334f24861 100644
--- a/src/services/rag/components/retrievers/lightrag.py
+++ b/src/services/rag/components/retrievers/lightrag.py
@@ -52,57 +52,17 @@ class LightRAGRetriever(BaseComponent):
try:
from lightrag import LightRAG
- from openai import AsyncOpenAI
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- # LLM function using services (ASYNC - LightRAG expects async functions)
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
- messages.extend(history_messages)
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
+ # Get model function from unified LLM client
+ # This handles all provider differences and env var setup for LightRAG
+ llm_model_func = llm_client.get_model_func()
# Create pure LightRAG instance (no multimodal)
rag = LightRAG(
diff --git a/src/services/rag/factory.py b/src/services/rag/factory.py
index fdf13de91..0516bf952 100644
--- a/src/services/rag/factory.py
+++ b/src/services/rag/factory.py
@@ -9,10 +9,12 @@ from typing import Callable, Dict, List, Optional
from .pipelines import lightrag, llamaindex
from .pipelines.raganything import RAGAnythingPipeline
+from .pipelines.raganything_docling import RAGAnythingDoclingPipeline
# Pipeline registry
_PIPELINES: Dict[str, Callable] = {
"raganything": RAGAnythingPipeline, # Full multimodal: MinerU parser, deep analysis (slow, thorough)
+ "raganything_docling": RAGAnythingDoclingPipeline, # Docling parser: Office/HTML friendly, easier setup
"lightrag": lightrag.LightRAGPipeline, # Knowledge graph: PDFParser, fast text-only (medium speed)
"llamaindex": llamaindex.LlamaIndexPipeline, # Vector-only: Simple chunking, fast (fastest)
}
@@ -41,12 +43,12 @@ def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, *
# Handle different pipeline types:
# - lightrag, academic: functions that return RAGPipeline
- # - llamaindex, raganything: classes that need instantiation
+ # - llamaindex, raganything, raganything_docling: classes that need instantiation
if name in ("lightrag", "academic"):
# LightRAGPipeline and AcademicPipeline are factory functions
return factory(kb_base_dir=kb_base_dir)
- elif name in ("llamaindex", "raganything"):
- # LlamaIndexPipeline and RAGAnythingPipeline are classes
+ elif name in ("llamaindex", "raganything", "raganything_docling"):
+ # LlamaIndexPipeline, RAGAnythingPipeline, and RAGAnythingDoclingPipeline are classes
if kb_base_dir:
kwargs["kb_base_dir"] = kb_base_dir
return factory(**kwargs)
@@ -75,8 +77,13 @@ def list_pipelines() -> List[Dict[str, str]]:
},
{
"id": "raganything",
- "name": "RAG-Anything",
- "description": "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
+ "name": "RAG-Anything (MinerU)",
+ "description": "Multimodal document processing with MinerU parser. Best for academic PDFs with complex equations and formulas.",
+ },
+ {
+ "id": "raganything_docling",
+ "name": "RAG-Anything (Docling)",
+ "description": "Multimodal document processing with Docling parser. Better for Office documents (.docx, .pptx) and HTML. Easier to install.",
},
]
diff --git a/src/services/rag/pipelines/__init__.py b/src/services/rag/pipelines/__init__.py
index 20c7f3297..7274f4492 100644
--- a/src/services/rag/pipelines/__init__.py
+++ b/src/services/rag/pipelines/__init__.py
@@ -9,9 +9,11 @@ from .academic import AcademicPipeline
from .lightrag import LightRAGPipeline
from .llamaindex import LlamaIndexPipeline
from .raganything import RAGAnythingPipeline
+from .raganything_docling import RAGAnythingDoclingPipeline
__all__ = [
"RAGAnythingPipeline",
+ "RAGAnythingDoclingPipeline",
"LightRAGPipeline",
"LlamaIndexPipeline",
"AcademicPipeline",
diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.py
index c072d8884..38dd2363c 100644
--- a/src/services/rag/pipelines/raganything.py
+++ b/src/services/rag/pipelines/raganything.py
@@ -9,11 +9,13 @@ from pathlib import Path
import sys
from typing import Any, Dict, List, Optional
-from lightrag.llm.openai import openai_complete_if_cache
-
from src.logging import get_logger
from src.logging.adapters import LightRAGLogContext
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
class RAGAnythingPipeline:
"""
@@ -71,106 +73,19 @@ class RAGAnythingPipeline:
self._setup_raganything_path()
- from openai import AsyncOpenAI
from raganything import RAGAnything, RAGAnythingConfig
from src.services.embedding import get_embedding_client
from src.services.llm import get_llm_client
+ # Use unified LLM client from src/services/llm
llm_client = get_llm_client()
embed_client = get_embedding_client()
- # Create AsyncOpenAI client directly - bypasses LightRAG's response_format handling
- openai_client = AsyncOpenAI(
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- )
-
- async def llm_model_func(prompt, system_prompt=None, history_messages=None, **kwargs):
- """Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""
- if history_messages is None:
- history_messages = []
-
- # Build messages array
- messages = []
- if system_prompt:
- messages.append({"role": "system", "content": system_prompt})
-
- # Add history
- messages.extend(history_messages)
-
- # Add current prompt
- messages.append({"role": "user", "content": prompt})
-
- # Whitelist only valid OpenAI parameters, filter out LightRAG-specific ones
- valid_params = {
- "temperature",
- "top_p",
- "n",
- "stream",
- "stop",
- "max_tokens",
- "presence_penalty",
- "frequency_penalty",
- "logit_bias",
- "user",
- "seed",
- }
- clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Call OpenAI API directly (async)
- response = await openai_client.chat.completions.create(
- model=llm_client.config.model,
- messages=messages,
- **clean_kwargs,
- )
-
- return response.choices[0].message.content
-
- def vision_model_func(
- prompt,
- system_prompt=None,
- history_messages=[],
- image_data=None,
- messages=None,
- **kwargs,
- ):
- # Handle multimodal messages
- if messages:
- clean_kwargs = {
- k: v
- for k, v in kwargs.items()
- if k not in ["messages", "prompt", "system_prompt", "history_messages"]
- }
- return openai_complete_if_cache(
- llm_client.config.model,
- prompt="",
- messages=messages,
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- **clean_kwargs,
- )
- if image_data:
- # Build image message
- image_message = {
- "role": "user",
- "content": [
- {"type": "text", "text": prompt},
- {
- "type": "image_url",
- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
- },
- ],
- }
- return openai_complete_if_cache(
- llm_client.config.model,
- prompt="",
- messages=[image_message],
- api_key=llm_client.config.api_key,
- base_url=llm_client.config.base_url,
- **kwargs,
- )
- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
config = RAGAnythingConfig(
working_dir=working_dir,
@@ -197,7 +112,15 @@ class RAGAnythingPipeline:
**kwargs,
) -> bool:
"""
- Initialize KB using RAG-Anything's process_document_complete().
+ Initialize KB using RAG-Anything with MinerU parser.
+
+ Processing flow:
+ 1. Parse documents using MinerU (generates content_list with nested image paths)
+ 2. Migrate images to canonical location (kb/images/) and update paths in content_list
+ 3. Insert updated content_list into RAG (now with correct image paths)
+ 4. Clean up temporary parser output directories
+
+ This ensures RAG stores the final image paths, avoiding path mismatches during retrieval.
Uses FileTypeRouter to classify files and route them appropriately:
- PDF files -> MinerU parser (full document analysis)
@@ -212,13 +135,21 @@ class RAGAnythingPipeline:
Returns:
True if successful
"""
+ import json
+
from ..components.routing import FileTypeRouter
+ from ..utils.image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+ )
self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")
kb_dir = Path(self.kb_base_dir) / kb_name
content_list_dir = kb_dir / "content_list"
+ images_dir = kb_dir / "images"
content_list_dir.mkdir(parents=True, exist_ok=True)
+ images_dir.mkdir(parents=True, exist_ok=True)
# Classify files by type
classification = FileTypeRouter.classify_files(file_paths)
@@ -235,19 +166,47 @@ class RAGAnythingPipeline:
total_files = len(classification.needs_mineru) + len(classification.text_files)
idx = 0
+ total_images_migrated = 0
# Process files requiring MinerU (PDF, DOCX, images)
for file_path in classification.needs_mineru:
idx += 1
- self.logger.info(
- f"Processing [{idx}/{total_files}] (MinerU): {Path(file_path).name}"
- )
- await rag.process_document_complete(
+ file_name = Path(file_path).name
+ self.logger.info(f"Processing [{idx}/{total_files}] (MinerU): {file_name}")
+
+ # Step 1: Parse document (without RAG insertion)
+ self.logger.info(" Step 1/3: Parsing document...")
+ content_list, doc_id = await rag.parse_document(
file_path=file_path,
output_dir=str(content_list_dir),
parse_method="auto",
)
+ # Step 2: Migrate images and update paths
+ self.logger.info(" Step 2/3: Migrating images to canonical location...")
+ updated_content_list, num_migrated = await migrate_images_and_update_paths(
+ content_list=content_list,
+ source_base_dir=content_list_dir,
+ target_images_dir=images_dir,
+ batch_size=50,
+ )
+ total_images_migrated += num_migrated
+
+ # Save updated content_list for future reference
+ content_list_file = content_list_dir / f"{Path(file_path).stem}.json"
+ with open(content_list_file, "w", encoding="utf-8") as f:
+ json.dump(updated_content_list, f, ensure_ascii=False, indent=2)
+
+ # Step 3: Insert into RAG with corrected paths
+ self.logger.info(" Step 3/3: Inserting into RAG knowledge graph...")
+ await rag.insert_content_list(
+ content_list=updated_content_list,
+ file_path=file_path,
+ doc_id=doc_id,
+ )
+
+ self.logger.info(f" ✓ Completed: {file_name}")
+
# Process text files directly (fast path)
for file_path in classification.text_files:
idx += 1
@@ -263,10 +222,17 @@ class RAGAnythingPipeline:
for file_path in classification.unsupported:
self.logger.warning(f"Skipped unsupported file: {Path(file_path).name}")
+ # Clean up temporary parser output directories
+ if total_images_migrated > 0:
+ self.logger.info("Cleaning up temporary parser output directories...")
+ await cleanup_parser_output_dirs(content_list_dir)
+
if extract_numbered_items:
await self._extract_numbered_items(kb_name)
- self.logger.info(f"KB '{kb_name}' initialized successfully")
+ self.logger.info(
+ f"KB '{kb_name}' initialized successfully ({total_images_migrated} images migrated)"
+ )
return True
async def _extract_numbered_items(self, kb_name: str):
diff --git a/src/services/rag/pipelines/raganything_docling.py b/src/services/rag/pipelines/raganything_docling.py
new file mode 100644
index 000000000..306534d5f
--- /dev/null
+++ b/src/services/rag/pipelines/raganything_docling.py
@@ -0,0 +1,368 @@
+"""
+RAGAnything Docling Pipeline
+============================
+
+End-to-end pipeline wrapping RAG-Anything with Docling parser for document processing.
+Uses Docling instead of MinerU for better Office document and HTML support.
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, Dict, List, Optional
+
+# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports
+# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly
+from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401
+
+from src.logging import get_logger
+from src.logging.adapters import LightRAGLogContext
+
+
+class RAGAnythingDoclingPipeline:
+ """
+ RAG-Anything Pipeline with Docling Parser.
+
+ Uses RAG-Anything's complete processing with Docling as the document parser:
+ - Docling document parsing (supports PDF, Office documents, HTML)
+ - LightRAG knowledge graph construction
+ - Hybrid retrieval (hybrid/local/global/naive modes)
+
+ Advantages over MinerU:
+ - Better support for Office documents (.doc, .docx, .ppt, .pptx, .xls, .xlsx)
+ - Native HTML parsing support
+ - Easier installation (no CUDA dependencies)
+
+ Note: For academic PDFs with complex equations and formulas,
+ use RAGAnythingPipeline (MinerU) instead for better accuracy.
+ """
+
+ name = "raganything_docling"
+
+ def __init__(
+ self,
+ kb_base_dir: Optional[str] = None,
+ enable_image_processing: bool = True,
+ enable_table_processing: bool = True,
+ enable_equation_processing: bool = True,
+ ):
+ """
+ Initialize RAGAnything Docling pipeline.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ enable_image_processing: Enable image extraction and processing
+ enable_table_processing: Enable table extraction and processing
+ enable_equation_processing: Enable equation extraction and processing
+ """
+ self.logger = get_logger("RAGAnythingDoclingPipeline")
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent / "data" / "knowledge_bases"
+ )
+ self.enable_image = enable_image_processing
+ self.enable_table = enable_table_processing
+ self.enable_equation = enable_equation_processing
+ self._instances: Dict[str, Any] = {}
+
+ def _setup_raganything_path(self):
+ """Add RAG-Anything to sys.path if available."""
+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent
+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+ if raganything_path.exists() and str(raganything_path) not in sys.path:
+ sys.path.insert(0, str(raganything_path))
+
+ def _get_rag_instance(self, kb_name: str):
+ """Get or create RAGAnything instance with Docling parser."""
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ if working_dir in self._instances:
+ return self._instances[working_dir]
+
+ self._setup_raganything_path()
+
+ from raganything import RAGAnything, RAGAnythingConfig
+
+ from src.services.embedding import get_embedding_client
+ from src.services.llm import get_llm_client
+
+ # Use unified LLM client from src/services/llm
+ llm_client = get_llm_client()
+ embed_client = get_embedding_client()
+
+ # Get model functions from unified LLM client
+ # These handle all provider differences (OpenAI, Anthropic, Azure, local, etc.)
+ llm_model_func = llm_client.get_model_func()
+ vision_model_func = llm_client.get_vision_model_func()
+
+ # Configure RAGAnything with Docling parser
+ # Note: content_format should be "auto" or "minerU" because DoclingParser
+ # converts its output to MinerU-compatible format internally
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ parser="docling", # Use Docling instead of MinerU
+ content_format="auto", # Auto-detect format (Docling outputs MinerU-compatible format)
+ enable_image_processing=self.enable_image,
+ enable_table_processing=self.enable_table,
+ enable_equation_processing=self.enable_equation,
+ )
+
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ vision_model_func=vision_model_func,
+ embedding_func=embed_client.get_embedding_func(),
+ )
+
+ self._instances[working_dir] = rag
+ return rag
+
+ async def initialize(
+ self,
+ kb_name: str,
+ file_paths: List[str],
+ extract_numbered_items: bool = True,
+ **kwargs,
+ ) -> bool:
+ """
+ Initialize KB using RAG-Anything with Docling parser.
+
+ Processing flow:
+ 1. Parse documents using Docling (generates content_list with nested image paths)
+ 2. Migrate images to canonical location (kb/images/) and update paths in content_list
+ 3. Insert updated content_list into RAG (now with correct image paths)
+ 4. Clean up temporary parser output directories
+
+ This ensures RAG stores the final image paths, avoiding path mismatches during retrieval.
+
+ Uses FileTypeRouter to classify files and route them appropriately:
+ - PDF files -> Docling parser
+ - Office files (.doc, .docx, .ppt, .pptx) -> Docling parser (direct support)
+ - HTML files -> Docling parser
+ - Text files -> Direct read + LightRAG insert (fast)
+
+ Args:
+ kb_name: Knowledge base name
+ file_paths: List of file paths to process
+ extract_numbered_items: Whether to extract numbered items after processing
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ import json
+
+ from ..components.routing import FileTypeRouter
+ from ..utils.image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+ )
+
+ self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files (Docling parser)")
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+ images_dir = kb_dir / "images"
+ content_list_dir.mkdir(parents=True, exist_ok=True)
+ images_dir.mkdir(parents=True, exist_ok=True)
+
+ # Classify files by type
+ classification = FileTypeRouter.classify_files(file_paths)
+
+ self.logger.info(
+ f"File classification: {len(classification.needs_mineru)} need Docling, "
+ f"{len(classification.text_files)} text files, "
+ f"{len(classification.unsupported)} unsupported"
+ )
+
+ with LightRAGLogContext(scene="knowledge_init"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ total_files = len(classification.needs_mineru) + len(classification.text_files)
+ idx = 0
+ total_images_migrated = 0
+
+ # Process files requiring Docling (PDF, DOCX, images, HTML)
+ for file_path in classification.needs_mineru:
+ idx += 1
+ file_name = Path(file_path).name
+ self.logger.info(
+ f"Processing [{idx}/{total_files}] (Docling): {file_name}"
+ )
+
+ # Step 1: Parse document (without RAG insertion)
+ self.logger.info(f" Step 1/3: Parsing document...")
+ content_list, doc_id = await rag.parse_document(
+ file_path=file_path,
+ output_dir=str(content_list_dir),
+ parse_method="auto",
+ )
+
+ # Step 2: Migrate images and update paths
+ self.logger.info(f" Step 2/3: Migrating images to canonical location...")
+ updated_content_list, num_migrated = await migrate_images_and_update_paths(
+ content_list=content_list,
+ source_base_dir=content_list_dir,
+ target_images_dir=images_dir,
+ batch_size=50,
+ )
+ total_images_migrated += num_migrated
+
+ # Save updated content_list for future reference
+ content_list_file = content_list_dir / f"{Path(file_path).stem}.json"
+ with open(content_list_file, "w", encoding="utf-8") as f:
+ json.dump(updated_content_list, f, ensure_ascii=False, indent=2)
+
+ # Step 3: Insert into RAG with corrected paths
+ self.logger.info(f" Step 3/3: Inserting into RAG knowledge graph...")
+ await rag.insert_content_list(
+ content_list=updated_content_list,
+ file_path=file_path,
+ doc_id=doc_id,
+ )
+
+ self.logger.info(f" ✓ Completed: {file_name}")
+
+ # Process text files directly (fast path)
+ for file_path in classification.text_files:
+ idx += 1
+ self.logger.info(
+ f"Processing [{idx}/{total_files}] (direct text): {Path(file_path).name}"
+ )
+ content = await FileTypeRouter.read_text_file(file_path)
+ if content.strip():
+ # Insert directly into LightRAG, bypassing parser
+ await rag.lightrag.ainsert(content)
+
+ # Log unsupported files
+ for file_path in classification.unsupported:
+ self.logger.warning(f"Skipped unsupported file: {Path(file_path).name}")
+
+ # Clean up temporary parser output directories
+ if total_images_migrated > 0:
+ self.logger.info("Cleaning up temporary parser output directories...")
+ await cleanup_parser_output_dirs(content_list_dir)
+
+ if extract_numbered_items:
+ await self._extract_numbered_items(kb_name)
+
+ self.logger.info(
+ f"KB '{kb_name}' initialized successfully with Docling parser "
+ f"({total_images_migrated} images migrated)"
+ )
+ return True
+
+ async def _extract_numbered_items(self, kb_name: str):
+ """Extract numbered items using existing extraction logic."""
+ try:
+ import json
+
+ from src.knowledge.extract_numbered_items import (
+ extract_numbered_items_with_llm_async,
+ )
+ from src.services.llm import get_llm_client
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+
+ if not content_list_dir.exists():
+ self.logger.warning("No content_list directory found, skipping extraction")
+ return
+
+ # Load all content list files
+ all_content_items = []
+ for json_file in content_list_dir.glob("*.json"):
+ with open(json_file, "r", encoding="utf-8") as f:
+ content_items = json.load(f)
+ all_content_items.extend(content_items)
+
+ if not all_content_items:
+ self.logger.warning("No content items found for extraction")
+ return
+
+ self.logger.info(
+ f"Extracting numbered items from {len(all_content_items)} content items"
+ )
+
+ llm_client = get_llm_client()
+ items = await extract_numbered_items_with_llm_async(
+ all_content_items,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ )
+
+ # Save numbered items
+ if items:
+ output_file = kb_dir / "numbered_items.json"
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(items, f, ensure_ascii=False, indent=2)
+ self.logger.info(f"Extracted {len(items)} numbered items")
+
+ except ImportError as e:
+ self.logger.warning(f"Could not import extraction module: {e}")
+ except Exception as e:
+ self.logger.error(f"Failed to extract numbered items: {e}")
+
+ async def search(
+ self,
+ query: str,
+ kb_name: str,
+ mode: str = "hybrid",
+ only_need_context: bool = False,
+ **kwargs,
+ ) -> Dict[str, Any]:
+ """
+ Search using RAG-Anything's aquery().
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ mode: Search mode (hybrid, local, global, naive)
+ only_need_context: Whether to only return context without answer
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ with LightRAGLogContext(scene="rag_search"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)
+ answer_str = answer if isinstance(answer, str) else str(answer)
+
+ return {
+ "query": query,
+ "answer": answer_str,
+ "content": answer_str,
+ "mode": mode,
+ "provider": "raganything_docling",
+ }
+
+ async def delete(self, kb_name: str) -> bool:
+ """
+ Delete knowledge base.
+
+ Args:
+ kb_name: Knowledge base name
+
+ Returns:
+ True if successful
+ """
+ import shutil
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ # Remove from cache
+ if working_dir in self._instances:
+ del self._instances[working_dir]
+
+ # Delete directory
+ if kb_dir.exists():
+ shutil.rmtree(kb_dir)
+ self.logger.info(f"Deleted KB '{kb_name}'")
+ return True
+
+ return False
+
diff --git a/src/services/rag/utils/__init__.py b/src/services/rag/utils/__init__.py
new file mode 100644
index 000000000..694b99d5c
--- /dev/null
+++ b/src/services/rag/utils/__init__.py
@@ -0,0 +1,17 @@
+"""
+RAG Utilities
+=============
+
+Utility modules for RAG operations.
+"""
+
+from .image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+)
+
+__all__ = [
+ "migrate_images_and_update_paths",
+ "cleanup_parser_output_dirs",
+]
+
diff --git a/src/services/rag/utils/image_migration.py b/src/services/rag/utils/image_migration.py
new file mode 100644
index 000000000..2785aa207
--- /dev/null
+++ b/src/services/rag/utils/image_migration.py
@@ -0,0 +1,296 @@
+"""
+Image Migration Utilities
+=========================
+
+Utilities for migrating images from parser output directories to the canonical
+knowledge base images directory, and updating content_list paths accordingly.
+
+This is needed because:
+1. Parsers (MinerU/Docling) output images to nested directories like:
+ content_list/{doc}/auto/images/ or content_list/{doc}/docling/images/
+2. RAG stores these paths in chunks, so if we move files later, retrieval breaks
+3. By migrating images BEFORE RAG indexing, we ensure correct paths are stored
+"""
+
+import asyncio
+import shutil
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+from concurrent.futures import ThreadPoolExecutor
+
+from src.logging import get_logger
+
+logger = get_logger("ImageMigration")
+
+# Maximum concurrent file operations to avoid overwhelming I/O
+MAX_CONCURRENT_COPIES = 10
+
+
+async def migrate_images_and_update_paths(
+ content_list: List[Dict[str, Any]],
+ source_base_dir: Path,
+ target_images_dir: Path,
+ batch_size: int = 50,
+) -> Tuple[List[Dict[str, Any]], int]:
+ """
+ Migrate images from parser output to canonical images directory and update paths.
+
+ This function:
+ 1. Scans content_list for image paths
+ 2. Copies images to target_images_dir (with deduplication)
+ 3. Updates content_list with new paths
+ 4. Returns updated content_list
+
+ Args:
+ content_list: Parsed content list from MinerU/Docling
+ source_base_dir: Base directory where parser outputs are located
+ target_images_dir: Canonical images directory (e.g., kb/images/)
+ batch_size: Number of images to process in each batch
+
+ Returns:
+ Tuple of (updated_content_list, num_images_migrated)
+ """
+ # Ensure target directory exists
+ target_images_dir.mkdir(parents=True, exist_ok=True)
+
+ # Collect all image items that need migration
+ image_items = []
+ for idx, item in enumerate(content_list):
+ if not isinstance(item, dict):
+ continue
+
+ # Check for image path in various fields
+ img_path = item.get("img_path") or item.get("image_path")
+ if img_path:
+ image_items.append((idx, img_path, "img_path" if "img_path" in item else "image_path"))
+
+ if not image_items:
+ logger.debug("No images found in content_list, skipping migration")
+ return content_list, 0
+
+ logger.info(f"Found {len(image_items)} images to migrate")
+
+ # Process images in batches to handle large quantities
+ migrated_count = 0
+ path_updates = {} # old_path -> new_path mapping
+
+ for batch_start in range(0, len(image_items), batch_size):
+ batch = image_items[batch_start:batch_start + batch_size]
+ batch_updates = await _process_image_batch(
+ batch, source_base_dir, target_images_dir
+ )
+ path_updates.update(batch_updates)
+ migrated_count += len([v for v in batch_updates.values() if v])
+
+ if batch_start + batch_size < len(image_items):
+ logger.info(f"Migrated {batch_start + len(batch)}/{len(image_items)} images...")
+
+ # Update content_list with new paths
+ updated_content_list = _update_content_list_paths(content_list, path_updates)
+
+ logger.info(f"Image migration complete: {migrated_count} images migrated")
+ return updated_content_list, migrated_count
+
+
+async def _process_image_batch(
+ batch: List[Tuple[int, str, str]],
+ source_base_dir: Path,
+ target_images_dir: Path,
+) -> Dict[str, str]:
+ """
+ Process a batch of images concurrently.
+
+ Args:
+ batch: List of (index, image_path, field_name) tuples
+ source_base_dir: Base directory for resolving relative paths
+ target_images_dir: Target directory for images
+
+ Returns:
+ Dict mapping old paths to new paths
+ """
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_COPIES)
+
+ async def copy_single_image(idx: int, img_path: str, field_name: str) -> Tuple[str, str]:
+ async with semaphore:
+ return await _migrate_single_image(
+ img_path, source_base_dir, target_images_dir
+ )
+
+ tasks = [
+ copy_single_image(idx, img_path, field_name)
+ for idx, img_path, field_name in batch
+ ]
+
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ path_updates = {}
+ for result in results:
+ if isinstance(result, Exception):
+ logger.warning(f"Error migrating image: {result}")
+ continue
+ old_path, new_path = result
+ if new_path:
+ path_updates[old_path] = new_path
+
+ return path_updates
+
+
+async def _migrate_single_image(
+ img_path: str,
+ source_base_dir: Path,
+ target_images_dir: Path,
+) -> Tuple[str, str]:
+ """
+ Migrate a single image file.
+
+ Args:
+ img_path: Original image path (may be absolute or relative)
+ source_base_dir: Base directory for resolving relative paths
+ target_images_dir: Target directory for images
+
+ Returns:
+ Tuple of (original_path, new_path) or (original_path, None) if failed
+ """
+ try:
+ # Resolve the source path
+ source_path = Path(img_path)
+ if not source_path.is_absolute():
+ source_path = source_base_dir / img_path
+
+ if not source_path.exists():
+ logger.warning(f"Source image not found: {img_path}")
+ return (img_path, None)
+
+ # Generate target filename (preserve original name)
+ target_filename = source_path.name
+ target_path = target_images_dir / target_filename
+
+ # Handle filename conflicts by adding suffix
+ if target_path.exists():
+ # Check if it's the same file (by size)
+ if target_path.stat().st_size == source_path.stat().st_size:
+ # Same file already exists, just update path
+ return (img_path, str(target_path))
+
+ # Different file with same name, add suffix
+ stem = source_path.stem
+ suffix = source_path.suffix
+ counter = 1
+ while target_path.exists():
+ target_filename = f"{stem}_{counter}{suffix}"
+ target_path = target_images_dir / target_filename
+ counter += 1
+
+ # Copy file using thread pool to avoid blocking
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ shutil.copy2,
+ str(source_path),
+ str(target_path)
+ )
+
+ logger.debug(f"Migrated: {source_path.name} -> {target_path}")
+ return (img_path, str(target_path))
+
+ except Exception as e:
+ logger.error(f"Failed to migrate image {img_path}: {e}")
+ return (img_path, None)
+
+
+def _update_content_list_paths(
+ content_list: List[Dict[str, Any]],
+ path_updates: Dict[str, str],
+) -> List[Dict[str, Any]]:
+ """
+ Update image paths in content_list with new paths.
+
+ Args:
+ content_list: Original content list
+ path_updates: Mapping of old paths to new paths
+
+ Returns:
+ Updated content list (new list, original is not modified)
+ """
+ updated_list = []
+
+ for item in content_list:
+ if not isinstance(item, dict):
+ updated_list.append(item)
+ continue
+
+ # Create a copy of the item
+ updated_item = dict(item)
+
+ # Update img_path if present
+ if "img_path" in updated_item:
+ old_path = updated_item["img_path"]
+ if old_path in path_updates and path_updates[old_path]:
+ updated_item["img_path"] = path_updates[old_path]
+
+ # Update image_path if present (alternative field name)
+ if "image_path" in updated_item:
+ old_path = updated_item["image_path"]
+ if old_path in path_updates and path_updates[old_path]:
+ updated_item["image_path"] = path_updates[old_path]
+
+ updated_list.append(updated_item)
+
+ return updated_list
+
+
+async def cleanup_parser_output_dirs(
+ content_list_dir: Path,
+ parser_subdirs: List[str] = None,
+) -> int:
+ """
+ Clean up parser output directories after successful migration.
+
+ Only removes the nested parser output directories (auto/, docling/),
+ NOT the content_list JSON files at the root level.
+
+ Args:
+ content_list_dir: The content_list directory
+ parser_subdirs: List of parser subdirectory names to clean
+
+ Returns:
+ Number of directories cleaned up
+ """
+ if parser_subdirs is None:
+ parser_subdirs = ["auto", "docling"]
+
+ cleaned_count = 0
+
+ for doc_dir in content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ for parser_subdir in parser_subdirs:
+ subdir = doc_dir / parser_subdir
+ if subdir.exists():
+ try:
+ # Run in thread pool to avoid blocking
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ shutil.rmtree,
+ str(subdir)
+ )
+ cleaned_count += 1
+ logger.debug(f"Cleaned up: {subdir}")
+ except Exception as e:
+ logger.warning(f"Failed to clean up {subdir}: {e}")
+
+ # Remove the doc_dir if it's now empty
+ try:
+ if doc_dir.exists() and not any(doc_dir.iterdir()):
+ doc_dir.rmdir()
+ logger.debug(f"Removed empty directory: {doc_dir}")
+ except Exception as e:
+ logger.debug(f"Could not remove directory {doc_dir}: {e}")
+
+ if cleaned_count > 0:
+ logger.info(f"Cleaned up {cleaned_count} parser output directories")
+
+ return cleaned_count
+
diff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.py
index 9f617f459..0f2212dbf 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,16 +20,17 @@ 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)
@@ -40,6 +41,7 @@ TEST_FILE = project_root / "tests" / "services" / "rag" / "testfile.txt"
class Colors:
"""Terminal colors"""
+
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
@@ -73,59 +75,57 @@ 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,22 +135,23 @@ 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 = [
@@ -158,31 +159,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:
@@ -192,22 +193,23 @@ 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,
@@ -215,52 +217,53 @@ class PipelineIntegrationTest:
kb_base_dir=self.temp_dir,
mode="naive",
)
-
+
if result and result.get("answer"):
- print_success(f"rag_tool.py search successful")
+ print_success("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,
@@ -270,26 +273,27 @@ 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
@@ -298,13 +302,14 @@ 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()]
@@ -318,43 +323,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
@@ -362,26 +367,23 @@ 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"
- )
- parser.add_argument(
- "--list", "-l",
- action="store_true",
- help="List available pipelines"
+ help="Pipeline to test (or 'all' for all pipelines). Default: llamaindex",
)
-
+ 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()
@@ -392,9 +394,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)
@@ -403,28 +405,23 @@ 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"
@@ -432,12 +429,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 bef019720..a20ac1fbc 100644
--- a/tests/services/rag/test_rag_pipelines.py
+++ b/tests/services/rag/test_rag_pipelines.py
@@ -10,19 +10,16 @@ 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
@@ -30,24 +27,25 @@ 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
@@ -60,7 +58,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.
@@ -94,185 +92,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, list_pipelines
-
+ from src.tools.rag_tool import get_available_providers
+
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(f"\n✓ Invalid pipeline correctly raises error")
+ print("\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)
@@ -281,275 +279,267 @@ 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 get_current_provider, DEFAULT_RAG_PROVIDER
-
+ from src.tools.rag_tool import DEFAULT_RAG_PROVIDER, get_current_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 PDFParser, MarkdownParser
-
+
+ from src.services.rag.components.parsers import MarkdownParser, PDFParser
+
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 (
- SemanticChunker, FixedSizeChunker, NumberedItemExtractor
+ FixedSizeChunker,
+ NumberedItemExtractor,
+ SemanticChunker,
)
-
+
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 VectorIndexer, GraphIndexer
-
+
+ from src.services.rag.components.indexers import GraphIndexer, VectorIndexer
+
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]}...")
@@ -562,19 +552,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()
@@ -591,18 +581,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 774a88dff..d8b190987 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.
\ No newline at end of file
+Shandong province has a pancake.
diff --git a/web/.env.local b/web/.env.local
index 0b6543af3..8840a64d6 100644
--- a/web/.env.local
+++ b/web/.env.local
@@ -3,7 +3,7 @@
# ============================================
# This file is automatically updated based on config/main.yaml
# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)
-#
+#
# To configure for remote access, set in your .env file:
# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001
# ============================================
diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsx
index ca8c8b145..b4090a181 100644
--- a/web/app/knowledge/page.tsx
+++ b/web/app/knowledge/page.tsx
@@ -1282,7 +1282,10 @@ export default function KnowledgePage() {
<>
<option value="llamaindex">LlamaIndex</option>
<option value="lightrag">LightRAG</option>
- <option value="raganything">RAG-Anything</option>
+ <option value="raganything">RAG-Anything (MinerU)</option>
+ <option value="raganything_docling">
+ RAG-Anything (Docling)
+ </option>
</>
)}
</select>
@@ -1303,7 +1306,9 @@ export default function KnowledgePage() {
lightrag:
"Lightweight knowledge graph retrieval, fast processing of text documents.",
raganything:
- "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
+ "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.",
};
return (
fallbackDescriptions[ragProvider] ||
@@ -1490,7 +1495,10 @@ export default function KnowledgePage() {
<>
<option value="llamaindex">LlamaIndex</option>
<option value="lightrag">LightRAG</option>
- <option value="raganything">RAG-Anything</option>
+ <option value="raganything">RAG-Anything (MinerU)</option>
+ <option value="raganything_docling">
+ RAG-Anything (Docling)
+ </option>
</>
)}
</select>
@@ -1510,7 +1518,9 @@ export default function KnowledgePage() {
lightrag:
"Lightweight knowledge graph retrieval, fast processing of text documents.",
raganything:
- "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
+ "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.",
};
return (
fallbackDescriptions[ragProvider] ||
diff --git a/web/app/settings/components/ConfigForm.tsx b/web/app/settings/components/ConfigForm.tsx
index de398cd93..e4b0d329e 100644
--- a/web/app/settings/components/ConfigForm.tsx
+++ b/web/app/settings/components/ConfigForm.tsx
@@ -432,8 +432,8 @@ export default function ConfigForm({
</label>
<input
type="number"
- value={dimensions}
- onChange={(e) => setDimensions(parseInt(e.target.value))}
+ value={Number.isNaN(dimensions) ? "" : dimensions}
+ onChange={(e) => setDimensions(parseInt(e.target.value, 10))}
className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
</div>