Skip to content

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

feat: add document incrementally

Pancake543b50739516
diff --git a/.env.example b/.env.example
index 03e231903..d94630af2 100644
--- a/.env.example
+++ b/.env.example
@@ -113,3 +113,16 @@ NEXT_PUBLIC_API_BASE=
# [Optional] Disable SSL verification (not recommended for production)
DISABLE_SSL_VERIFY=false
+
+# ==============================
+# HuggingFace / MinerU (Optional)
+# ==============================
+
+# Use a HuggingFace mirror endpoint (optional)
+# HF_ENDPOINT=https://your-hf-mirror.example.com
+
+# HuggingFace cache directory (recommended: mount this in Docker to reuse cache)
+# HF_HOME=/app/data/hf
+
+# Force offline mode (requires models already downloaded into the cache)
+# HF_HUB_OFFLINE=1
\ No newline at end of file
diff --git a/.env.example_CN b/.env.example_CN
index dee5c6108..20e64690c 100644
--- a/.env.example_CN
+++ b/.env.example_CN
@@ -113,3 +113,16 @@ NEXT_PUBLIC_API_BASE=
# [可选] 禁用 SSL 证书验证(生产环境不建议启用)
DISABLE_SSL_VERIFY=false
+
+# ==============================
+# HuggingFace / MinerU(可选)
+# ==============================
+
+# 使用 HuggingFace 镜像站点(可选)
+# HF_ENDPOINT=https://your-hf-mirror.example.com
+
+# HuggingFace 缓存目录(建议:Docker 场景配合挂载该目录以复用缓存)
+# HF_HOME=/app/data/hf
+
+# 强制离线模式(前提:模型已在上述缓存目录中下载好)
+# HF_HUB_OFFLINE=1
\ No newline at end of file
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index fbbf2c44b..1069b399b 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -1,22 +1,18 @@
name: Build and Publish Docker Image
on:
- # Trigger on release publication
- release:
- types: [published]
-
- # Trigger on version tags
- push:
- tags:
- - "v*.*.*"
-
- # Allow manual trigger
+ # Manual trigger only - gives full control over when images are published
workflow_dispatch:
inputs:
- tag:
- description: "Docker image tag (e.g., latest, v0.2.0)"
- required: false
- default: "latest"
+ version:
+ description: "Version tag (e.g., 0.5.2, 0.6.0) - without 'v' prefix"
+ required: true
+ type: string
+ push_latest:
+ description: "Also update the 'latest' tag?"
+ required: true
+ type: boolean
+ default: true
env:
REGISTRY: ghcr.io
@@ -24,19 +20,20 @@ env:
jobs:
# ============================================
- # Build AMD64 Image (Intel/AMD processors)
+ # Build Multi-Architecture Docker Image
+ # ============================================
+ # This job builds both AMD64 and ARM64 images and creates
+ # a multi-arch manifest so Docker automatically pulls the
+ # correct architecture for each user's system.
# ============================================
- build-amd64:
- name: Build AMD64 Image
+ build-multiarch:
+ name: Build Multi-Arch Image
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
- outputs:
- digest: ${{ steps.build.outputs.digest }}
-
steps:
- name: Free disk space
uses: jlumbroso/free-disk-space@main
@@ -50,7 +47,10 @@ jobs:
swap-storage: true
- name: Checkout repository
- uses: actions/checkout@v6
+ uses: actions/checkout@v4
+
+ - name: Set up QEMU
+ uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -62,24 +62,28 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- - name: Extract metadata for AMD64
- id: meta
- uses: docker/metadata-action@v5
- with:
- images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- tags: |
- # For releases: version tag (v0.2.0 -> 0.2.0)
- type=semver,pattern={{version}}
- # For releases: major.minor (v0.2.0 -> 0.2)
- type=semver,pattern={{major}}.{{minor}}
- # For releases: tag as latest (default for amd64)
- type=raw,value=latest,enable=${{ github.event_name == 'release' }}
- # For manual trigger: use input tag
- type=raw,value=${{ github.event.inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' }}
- # For push tags: use the tag name
- type=ref,event=tag
-
- - name: Build and push AMD64 image
+ - name: Validate and set version
+ id: version
+ run: |
+ VERSION="${{ github.event.inputs.version }}"
+
+ # Validate version format (e.g., 0.5.2, 1.0.0)
+ if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "❌ Error: Invalid version format '$VERSION'"
+ echo " Expected format: X.Y.Z (e.g., 0.5.2, 1.0.0)"
+ exit 1
+ fi
+
+ echo "version=${VERSION}" >> $GITHUB_OUTPUT
+ echo "📌 Version: ${VERSION}"
+ echo "📌 Push latest: ${{ github.event.inputs.push_latest }}"
+
+ # ============================================
+ # Build and push multi-arch image
+ # Docker will automatically create a manifest list
+ # that includes both architectures
+ # ============================================
+ - name: Build and push multi-arch image
id: build
uses: docker/build-push-action@v6
with:
@@ -87,125 +91,88 @@ jobs:
file: ./Dockerfile
target: production
push: true
- tags: ${{ steps.meta.outputs.tags }}
- labels: ${{ steps.meta.outputs.labels }}
- platforms: linux/amd64
- cache-from: type=gha,scope=amd64
- cache-to: type=gha,mode=max,scope=amd64
+ # Build for both architectures in a single command
+ platforms: linux/amd64,linux/arm64
+ tags: |
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}
+ labels: |
+ org.opencontainers.image.title=DeepTutor
+ org.opencontainers.image.description=AI-Powered Personalized Learning Assistant
+ org.opencontainers.image.version=${{ steps.version.outputs.version }}
+ org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
+ org.opencontainers.image.revision=${{ github.sha }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
build-args: |
BACKEND_PORT=8001
provenance: false
- # ============================================
- # Build ARM64 Image (Apple Silicon, ARM servers)
- # ============================================
- build-arm64:
- name: Build ARM64 Image
- runs-on: ubuntu-latest
+ # ============================================
+ # Update 'latest' tag if requested
+ # ============================================
+ - name: Tag as latest
+ if: github.event.inputs.push_latest == 'true'
+ run: |
+ VERSION="${{ steps.version.outputs.version }}"
- permissions:
- contents: read
- packages: write
+ echo "🏷️ Tagging ${VERSION} as latest..."
- outputs:
- digest: ${{ steps.build.outputs.digest }}
+ # Pull the manifest and retag as latest
+ docker buildx imagetools create \
+ --tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \
+ ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}
- steps:
- - name: Free disk space
- uses: jlumbroso/free-disk-space@main
- with:
- tool-cache: true
- android: true
- dotnet: true
- haskell: true
- large-packages: true
- docker-images: true
- swap-storage: true
+ echo "✅ Successfully tagged as latest"
- - name: Checkout repository
- uses: actions/checkout@v6
+ # ============================================
+ # Create architecture-specific tags for compatibility
+ # Some users may prefer explicit architecture tags
+ # ============================================
+ - name: Create architecture-specific tags
+ run: |
+ VERSION="${{ steps.version.outputs.version }}"
+ IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
- - name: Set up QEMU
- uses: docker/setup-qemu-action@v3
+ echo "🏷️ Creating architecture-specific tags..."
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v3
+ # Create version-specific architecture tags
+ # These are optional convenience tags for users who want explicit control
- - name: Log in to Container Registry
- uses: docker/login-action@v3
- with:
- registry: ${{ env.REGISTRY }}
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
+ # For AMD64
+ docker buildx imagetools create \
+ --tag ${IMAGE}:${VERSION}-amd64 \
+ ${IMAGE}:${VERSION} --platform linux/amd64 || true
- - name: Extract metadata for ARM64
- id: meta
- uses: docker/metadata-action@v5
- with:
- images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- tags: |
- # For releases: version-arm64 (v0.2.0 -> 0.2.0-arm64)
- type=semver,pattern={{version}}-arm64
- # For releases: major.minor-arm64 (v0.2.0 -> 0.2-arm64)
- type=semver,pattern={{major}}.{{minor}}-arm64
- # For releases: tag as latest-arm64
- type=raw,value=latest-arm64,enable=${{ github.event_name == 'release' }}
- # For manual trigger: use input tag with -arm64 suffix
- type=raw,value=${{ github.event.inputs.tag }}-arm64,enable=${{ github.event_name == 'workflow_dispatch' }}
- # For push tags: use the tag name with -arm64 suffix
- 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: .
- file: ./Dockerfile
- target: production
- push: true
- tags: ${{ steps.meta.outputs.tags }}
- labels: ${{ steps.meta.outputs.labels }}
- platforms: linux/arm64
- cache-from: type=gha,scope=arm64
- 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'
+ # For ARM64
+ docker buildx imagetools create \
+ --tag ${IMAGE}:${VERSION}-arm64 \
+ ${IMAGE}:${VERSION} --platform linux/arm64 || true
- permissions:
- contents: read
- packages: write
+ # Create latest-arm64 for backward compatibility (only if pushing latest)
+ if [ "${{ github.event.inputs.push_latest }}" == "true" ]; then
+ docker buildx imagetools create \
+ --tag ${IMAGE}:latest-arm64 \
+ ${IMAGE}:latest --platform linux/arm64 || true
+ fi
- steps:
- - name: Log in to Container Registry
- uses: docker/login-action@v3
- with:
- registry: ${{ env.REGISTRY }}
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
+ echo "✅ Architecture-specific tags created"
- - name: Create and push multi-arch manifest
+ # ============================================
+ # Verify the multi-arch manifest
+ # ============================================
+ - name: Verify 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
+ VERSION="${{ steps.version.outputs.version }}"
+ IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
- docker manifest push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${VERSION}-multi
+ echo "🔍 Verifying multi-arch manifest for ${IMAGE}:${VERSION}..."
+ docker buildx imagetools inspect ${IMAGE}:${VERSION}
- echo "✅ Created multi-arch manifest: ${VERSION}-multi"
+ if [ "${{ github.event.inputs.push_latest }}" == "true" ]; then
+ echo ""
+ echo "🔍 Verifying multi-arch manifest for ${IMAGE}:latest..."
+ docker buildx imagetools inspect ${IMAGE}:latest
+ fi
# ============================================
# Generate Summary
@@ -213,48 +180,70 @@ jobs:
summary:
name: Generate Summary
runs-on: ubuntu-latest
- needs: [build-amd64, build-arm64]
+ needs: [build-multiarch]
if: always()
steps:
+ - name: Get version
+ id: version
+ run: |
+ echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
+
- name: Generate image summary
run: |
+ VERSION="${{ steps.version.outputs.version }}"
+
echo "## 🐳 Docker Images Build Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Registry:** \`${{ env.REGISTRY }}\`" >> $GITHUB_STEP_SUMMARY
+ echo "**Version:** \`${VERSION}\`" >> $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
+ if [ "${{ needs.build-multiarch.result }}" == "success" ]; then
+ echo "✅ **Multi-arch build successful!**" >> $GITHUB_STEP_SUMMARY
+ else
+ echo "❌ **Build failed**" >> $GITHUB_STEP_SUMMARY
+ fi
echo "" >> $GITHUB_STEP_SUMMARY
+
echo "### Available Images" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
- echo "| Architecture | Image Tag | Use Case |" >> $GITHUB_STEP_SUMMARY
- echo "|--------------|-----------|----------|" >> $GITHUB_STEP_SUMMARY
- echo "| **AMD64** | \`latest\` | Intel/AMD processors (most cloud servers, Windows/Linux PCs) |" >> $GITHUB_STEP_SUMMARY
- echo "| **ARM64** | \`latest-arm64\` | Apple Silicon (M1/M2/M3/M4), ARM servers (AWS Graviton, etc.) |" >> $GITHUB_STEP_SUMMARY
+ echo "| Tag | Architectures | Description |" >> $GITHUB_STEP_SUMMARY
+ echo "|-----|---------------|-------------|" >> $GITHUB_STEP_SUMMARY
+ echo "| \`:latest\` | AMD64, ARM64 | Latest stable release (auto-detects architecture) |" >> $GITHUB_STEP_SUMMARY
+ echo "| \`:${VERSION}\` | AMD64, ARM64 | Version ${VERSION} (auto-detects architecture) |" >> $GITHUB_STEP_SUMMARY
+ echo "| \`:${VERSION}-amd64\` | AMD64 only | Explicit AMD64 image |" >> $GITHUB_STEP_SUMMARY
+ echo "| \`:${VERSION}-arm64\` | ARM64 only | Explicit ARM64 image |" >> $GITHUB_STEP_SUMMARY
+ echo "| \`:latest-arm64\` | ARM64 only | Latest ARM64 (backward compatibility) |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
+
echo "### Quick Start" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
- echo "**For AMD64 (Intel/AMD):**" >> $GITHUB_STEP_SUMMARY
+ echo "**Recommended (auto-detects your architecture):**" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
echo "docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
- echo "**For ARM64 (Apple Silicon/ARM servers):**" >> $GITHUB_STEP_SUMMARY
- echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
- echo "docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest-arm64" >> $GITHUB_STEP_SUMMARY
- echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
- echo "" >> $GITHUB_STEP_SUMMARY
echo "**Run the container:**" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
- echo "docker run -d -p 8001:8001 -p 3782:3782 \\\\" >> $GITHUB_STEP_SUMMARY
+ echo "docker run -d --name deeptutor \\\\" >> $GITHUB_STEP_SUMMARY
+ echo " -p 8001:8001 -p 3782:3782 \\\\" >> $GITHUB_STEP_SUMMARY
echo " -e LLM_MODEL=gpt-4o \\\\" >> $GITHUB_STEP_SUMMARY
- echo " -e LLM_BINDING_API_KEY=your-api-key \\\\" >> $GITHUB_STEP_SUMMARY
+ echo " -e LLM_API_KEY=your-api-key \\\\" >> $GITHUB_STEP_SUMMARY
echo " -e EMBEDDING_MODEL=text-embedding-3-large \\\\" >> $GITHUB_STEP_SUMMARY
- echo " -e EMBEDDING_BINDING_API_KEY=your-api-key \\\\" >> $GITHUB_STEP_SUMMARY
- echo " ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest # or :latest-arm64" >> $GITHUB_STEP_SUMMARY
+ echo " -e EMBEDDING_API_KEY=your-api-key \\\\" >> $GITHUB_STEP_SUMMARY
+ echo " -v \$(pwd)/data:/app/data \\\\" >> $GITHUB_STEP_SUMMARY
+ echo " -v \$(pwd)/config:/app/config:ro \\\\" >> $GITHUB_STEP_SUMMARY
+ echo " ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+
+ echo "### Architecture Detection" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "The \`:latest\` and \`:${VERSION}\` tags are **multi-architecture images**." >> $GITHUB_STEP_SUMMARY
+ echo "Docker will automatically pull the correct image for your system:" >> $GITHUB_STEP_SUMMARY
+ echo "" >> $GITHUB_STEP_SUMMARY
+ echo "- **AMD64**: Intel/AMD processors (most Windows PCs, Linux servers)" >> $GITHUB_STEP_SUMMARY
+ echo "- **ARM64**: Apple Silicon (M1/M2/M3/M4), AWS Graviton, Raspberry Pi 4+" >> $GITHUB_STEP_SUMMARY
diff --git a/README.md b/README.md
index 7d2998b72..d75acaf26 100644
--- a/README.md
+++ b/README.md
@@ -345,7 +345,7 @@ docker compose build --no-cache # Clear cache and rebuild after pull the newe
**Or use pre-built image** (faster):
```bash
-# Linux/macOS (AMD64)
+# Works on all platforms - Docker auto-detects your architecture
docker run -d --name deeptutor \
-p 8001:8001 -p 3782:3782 \
--env-file .env \
@@ -353,7 +353,6 @@ docker run -d --name deeptutor \
-v $(pwd)/config:/app/config:ro \
ghcr.io/hkuds/deeptutor:latest
-# Apple Silicon (ARM64): use ghcr.io/hkuds/deeptutor:latest-arm64
# Windows PowerShell: use ${PWD} instead of $(pwd)
```
@@ -369,14 +368,16 @@ docker compose up --build # Rebuild after changes
<details>
<summary>📋 <b>More Docker Options</b> (Pre-built images, Cloud deployment, Custom ports)</summary>
-**Pre-built Image Architecture Reference:**
+**Pre-built Image Tags:**
-| Architecture | Image Tag | Use Case |
-|:-------------|:----------|:---------|
-| **AMD64** | `ghcr.io/hkuds/deeptutor:latest` | Intel/AMD (most servers, Windows/Linux PCs) |
-| **ARM64** | `ghcr.io/hkuds/deeptutor:latest-arm64` | Apple Silicon, AWS Graviton, Raspberry Pi |
+| Tag | Architectures | Description |
+|:----|:--------------|:------------|
+| `:latest` | AMD64 + ARM64 | Latest stable release (auto-detects your architecture) |
+| `:v0.5.x` | AMD64 + ARM64 | Specific version (auto-detects your architecture) |
+| `:v0.5.x-amd64` | AMD64 only | Explicit AMD64 image |
+| `:v0.5.x-arm64` | ARM64 only | Explicit ARM64 image |
-> 💡 Run `uname -m` to check: `x86_64` = AMD64, `arm64`/`aarch64` = ARM64
+> 💡 The `:latest` tag is a **multi-architecture image** — Docker automatically pulls the correct version for your system (Intel/AMD or Apple Silicon/ARM)
**Cloud Deployment** — Must set external API URL:
diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md
index 1cb773b4f..f459c0b60 100644
--- a/docs/guide/configuration.md
+++ b/docs/guide/configuration.md
@@ -144,6 +144,24 @@ TTS_URL=
TTS_API_KEY=
```
+## 🤗 HuggingFace / MinerU (Optional, for offline or mirrored networks)
+
+If your environment cannot access `huggingface.co` directly (common in restricted networks), MinerU may fail when it tries to download models from the HuggingFace Hub. DeepTutor reads your root `.env` (Docker Compose uses `env_file: .env`), so you can **optionally** add the following variables:
+
+```bash
+# ============================================================================
+# HuggingFace Hub / MinerU - Optional
+# ============================================================================
+# Use a HuggingFace mirror endpoint (if you have one)
+# HF_ENDPOINT=https://your-hf-mirror.example.com
+
+# Persist/cache directory (inside container). For Docker, consider mounting this path.
+# HF_HOME=/app/data/hf
+
+# Force offline mode (requires models already cached locally)
+# HF_HUB_OFFLINE=1
+```
+
## 🔌 Supported Providers
### LLM Providers
diff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.md
index 1db52ef0c..42524981b 100644
--- a/docs/zh/guide/configuration.md
+++ b/docs/zh/guide/configuration.md
@@ -45,6 +45,24 @@ TTS_URL=
TTS_API_KEY=
```
+## 🤗 HuggingFace / MinerU(可选:离线/镜像网络)
+
+如果你的环境无法直接访问 `huggingface.co`(比如内网/校园网/离线环境),MinerU 在尝试从 HuggingFace Hub 下载模型时可能会失败。DeepTutor 会读取根目录 `.env`(并且 `docker-compose.yml` 通过 `env_file: .env` 注入到容器),因此你可以在 `.env` 里**按需添加**下面这些变量:
+
+```bash
+# ============================================================================
+# HuggingFace Hub / MinerU - 可选
+# ============================================================================
+# 使用 HuggingFace 镜像站点(如果你有可用的镜像域名)
+# HF_ENDPOINT=https://your-hf-mirror.example.com
+
+# 缓存目录(容器内路径)。Docker 建议把该目录挂载出来以便复用缓存。
+# HF_HOME=/app/data/hf
+
+# 强制离线模式(前提:模型已在本地缓存中)
+# HF_HUB_OFFLINE=1
+```
+
## Agent 参数
编辑 `config/agents.yaml`:
diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.py
index 5982a8f94..4d0eb8dd6 100644
--- a/src/api/routers/knowledge.py
+++ b/src/api/routers/knowledge.py
@@ -142,8 +142,19 @@ async def run_upload_processing_task(
base_url: str,
uploaded_file_paths: list[str],
rag_provider: str = None,
+ folder_id: str = None,
):
- """Background task for processing uploaded files"""
+ """Background task for processing uploaded files.
+
+ Args:
+ kb_name: Knowledge base name
+ base_dir: Base directory for knowledge bases
+ api_key: LLM API key
+ base_url: LLM API base URL
+ uploaded_file_paths: List of file paths to process
+ rag_provider: RAG provider (ignored - we use the one from KB metadata)
+ folder_id: Optional folder ID for sync state update
+ """
task_manager = TaskIDManager.get_instance()
task_key = f"{kb_name}_upload_{len(uploaded_file_paths)}"
task_id = task_manager.generate_task_id("kb_upload", task_key)
@@ -169,8 +180,22 @@ async def run_upload_processing_task(
rag_provider=rag_provider,
)
- new_files = [Path(path) for path in uploaded_file_paths]
- processed_files = await adder.process_new_documents(new_files)
+ # Stage files and check for duplicates
+ staged_files = adder.add_documents(uploaded_file_paths, allow_duplicates=False)
+
+ if not staged_files:
+ logger.info(f"[{task_id}] No new files to process (all duplicates or invalid)")
+ progress_tracker.update(
+ ProgressStage.COMPLETED,
+ "No new files to process (all duplicates or invalid)",
+ current=0,
+ total=0,
+ )
+ task_manager.update_task_status(task_id, "completed")
+ return
+
+ # Process staged files
+ processed_files = await adder.process_new_documents(staged_files)
if processed_files:
progress_tracker.update(
@@ -181,16 +206,28 @@ async def run_upload_processing_task(
)
adder.extract_numbered_items_for_new_docs(processed_files, batch_size=20)
- adder.update_metadata(len(new_files))
+ adder.update_metadata(len(processed_files) if processed_files else 0)
+
+ # Update folder sync state if this was a folder sync
+ if folder_id and processed_files:
+ try:
+ manager = get_kb_manager()
+ manager.update_folder_sync_state(
+ kb_name, folder_id, [str(f) for f in processed_files]
+ )
+ logger.info(f"[{task_id}] Updated folder sync state for folder '{folder_id}'")
+ except Exception as sync_err:
+ logger.warning(f"[{task_id}] Failed to update folder sync state: {sync_err}")
+ num_processed = len(processed_files) if processed_files else 0
progress_tracker.update(
ProgressStage.COMPLETED,
- f"Successfully processed {len(processed_files)} files!",
- current=len(processed_files),
- total=len(processed_files),
+ f"Successfully processed {num_processed} files!",
+ current=num_processed,
+ total=num_processed,
)
- logger.success(f"[{task_id}] Processed {len(processed_files)} files to KB '{kb_name}'")
+ logger.success(f"[{task_id}] Processed {num_processed} files to KB '{kb_name}'")
task_manager.update_task_status(task_id, "completed")
except Exception as e:
error_msg = f"Upload processing failed (KB '{kb_name}'): {e}"
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
index 7e8cdfeb6..74a1f68e1 100644
--- a/src/knowledge/add_documents.py
+++ b/src/knowledge/add_documents.py
@@ -4,6 +4,12 @@
Incrementally add documents to existing knowledge base.
Improved version with Hash-based duplicate checking, robust error handling,
and architectural improvements for data integrity and vision support.
+
+Supports multiple RAG providers with lazy loading:
+- llamaindex: Pure vector retrieval (load_index + insert + persist)
+- lightrag: Knowledge graph (LightRAG.ainsert, text-only)
+- raganything: Multimodal with MinerU parser
+- raganything_docling: Multimodal with Docling parser
"""
import argparse
@@ -17,7 +23,7 @@ from pathlib import Path
import shutil
import sys
import tempfile
-from typing import TYPE_CHECKING, Any, Dict, List
+from typing import Any, Dict, List
from dotenv import load_dotenv
@@ -25,56 +31,8 @@ from dotenv import load_dotenv
# 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.utils import EmbeddingFunc
-except ImportError:
- # This will be caught during runtime if needed
- EmbeddingFunc = None
-
-# Type hinting support for dynamic imports
-if TYPE_CHECKING:
- try:
- from raganything import RAGAnything
- from raganything import RAGAnythingConfig as RAGAnythingConfigType
- except ImportError:
- RAGAnything = Any
- RAGAnythingConfigType = Any
-else:
- RAGAnything = None
- RAGAnythingConfigType = None
-
-# Placeholder for runtime classes
-raganything_cls = None
-RAGAnythingConfig = None
-
-
-def load_dynamic_imports(project_root: Path):
- """Handle the path injections and dynamic imports safely."""
- global raganything_cls, RAGAnythingConfig
-
- sys.path.insert(0, str(project_root))
- raganything_path = project_root.parent / "raganything" / "RAG-Anything"
- if raganything_path.exists():
- sys.path.insert(0, str(raganything_path))
-
- try:
- from raganything import RAGAnything as RA
- from raganything import RAGAnythingConfig as RAC
-
- raganything_cls = RA
- RAGAnythingConfig = RAC
- except ImportError:
- pass
-
-
from src.knowledge.extract_numbered_items import process_content_list
from src.logging import LightRAGLogContext, get_logger
-from src.services.embedding import (
- get_embedding_client,
- get_embedding_config,
- reset_embedding_client,
-)
from src.services.llm import get_llm_config
logger = get_logger("KnowledgeInit")
@@ -84,7 +42,14 @@ DEFAULT_BASE_DIR = "./data/knowledge_bases"
class DocumentAdder:
- """Add documents to existing knowledge base with Hash-validation"""
+ """Add documents to existing knowledge base with Hash-validation.
+
+ Supports multiple RAG providers with lazy loading to avoid unnecessary imports:
+ - llamaindex: Only imports llama_index modules
+ - lightrag: Only imports lightrag modules (no raganything)
+ - raganything: Imports raganything with MinerU parser
+ - raganything_docling: Imports raganything with Docling parser
+ """
def __init__(
self,
@@ -108,14 +73,60 @@ class DocumentAdder:
self.content_list_dir = self.kb_dir / "content_list"
self.metadata_file = self.kb_dir / "metadata.json"
- if not self.rag_storage_dir.exists():
- raise ValueError(f"Knowledge base not initialized: {kb_name}")
+ # For llamaindex, check llamaindex_storage instead of rag_storage
+ provider = self._get_provider_from_metadata()
+ if provider == "llamaindex":
+ llamaindex_storage = self.kb_dir / "llamaindex_storage"
+ if not llamaindex_storage.exists():
+ raise ValueError(f"Knowledge base not initialized (llamaindex): {kb_name}")
+ else:
+ if not self.rag_storage_dir.exists():
+ raise ValueError(f"Knowledge base not initialized: {kb_name}")
self.api_key = api_key
self.base_url = base_url
self.progress_tracker = progress_tracker
- self.rag_provider = rag_provider
+
+ # IMPORTANT: rag_provider parameter is IGNORED for incremental add
+ # We always use the provider from KB metadata to ensure consistency
+ # This prevents mixing different index formats in the same KB
+ self._resolved_provider = provider
+ if rag_provider and rag_provider != provider:
+ logger.warning(
+ f"Requested provider '{rag_provider}' ignored. "
+ f"Using KB's existing provider '{provider}' for consistency."
+ )
+ logger.info(f"Incremental add will use provider: {provider} (from KB metadata)")
self._ensure_working_directories()
+
+ def _get_provider_from_metadata(self) -> str:
+ """
+ Get the RAG provider from KB metadata.
+
+ This is the ONLY source of truth for incremental adds - we must use
+ the same provider that was used during initialization to ensure
+ data consistency and correct storage format.
+
+ Returns:
+ Provider name (llamaindex, lightrag, raganything, raganything_docling)
+ """
+ if self.metadata_file.exists():
+ try:
+ with open(self.metadata_file, "r", encoding="utf-8") as f:
+ metadata = json.load(f)
+ provider = metadata.get("rag_provider")
+ if provider:
+ return provider
+ except Exception as e:
+ logger.warning(f"Failed to read provider from metadata: {e}")
+
+ # Fallback: detect from storage structure
+ llamaindex_storage = self.kb_dir / "llamaindex_storage"
+ if llamaindex_storage.exists():
+ return "llamaindex"
+
+ # Default to raganything for backward compatibility
+ return "raganything"
def _ensure_working_directories(self):
for directory in [self.raw_dir, self.images_dir, self.content_list_dir]:
@@ -203,36 +214,261 @@ class DocumentAdder:
async def process_new_documents(self, new_files: List[Path]):
"""
Async phase: Ingests files into the RAG system.
-
- Uses FileTypeRouter to classify files and route them appropriately:
- - PDF/DOCX/images -> MinerU parser (full document analysis)
- - Text/Markdown -> Direct read + LightRAG insert (fast)
+
+ Uses lazy loading to only import dependencies for the actual provider:
+ - llamaindex: Only imports llama_index
+ - lightrag: Only imports lightrag (no raganything)
+ - raganything: Imports raganything with MinerU
+ - raganything_docling: Imports raganything with Docling
"""
if not new_files:
return None
- if raganything_cls is None:
- raise ImportError("RAGAnything module not found.")
+ provider = self._resolved_provider
+ logger.info(f"Processing {len(new_files)} files with provider: {provider}")
+
+ # Dispatch to provider-specific implementation
+ if provider == "llamaindex":
+ return await self._process_llamaindex(new_files)
+ elif provider == "lightrag":
+ return await self._process_lightrag(new_files)
+ elif provider == "raganything":
+ return await self._process_raganything(new_files, parser="mineru")
+ elif provider == "raganything_docling":
+ return await self._process_raganything(new_files, parser="docling")
+ else:
+ raise ValueError(f"Unknown RAG provider: {provider}")
+
+ async def _process_llamaindex(self, new_files: List[Path]) -> List[Path]:
+ """
+ Incremental add for LlamaIndex pipeline.
+ Lazy imports llama_index only when needed.
+ """
+ logger.info("Using LlamaIndex incremental add...")
+
+ # Lazy import llama_index
+ try:
+ from src.services.rag.pipelines.llamaindex import LlamaIndexPipeline
+ except ImportError as e:
+ raise ImportError(
+ f"LlamaIndex dependencies not installed. "
+ f"Install with: pip install llama-index llama-index-core. Error: {e}"
+ ) from e
+
+ # Pre-import progress stage if needed
+ ProgressStage: Any = None
+ if self.progress_tracker:
+ from src.knowledge.progress_tracker import ProgressStage
+
+ pipeline = LlamaIndexPipeline(kb_base_dir=str(self.base_dir))
+ file_paths = [str(f) for f in new_files]
+
+ # Use the new add_documents method for incremental add
+ processed_files = []
+ total_files = len(file_paths)
+
+ for idx, file_path in enumerate(file_paths, 1):
+ doc_file = Path(file_path)
+ try:
+ if self.progress_tracker and ProgressStage:
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_FILE,
+ f"Indexing (LlamaIndex) {doc_file.name}",
+ current=idx,
+ total=total_files,
+ )
+
+ # Use add_documents for incremental add
+ success = await pipeline.add_documents(self.kb_name, [file_path])
+ if success:
+ processed_files.append(doc_file)
+ self._record_successful_hash(doc_file)
+ logger.info(f" ✓ Processed (LlamaIndex): {doc_file.name}")
+ else:
+ logger.error(f" ✗ Failed to index: {doc_file.name}")
+ except Exception as e:
+ logger.exception(f" ✗ Failed {doc_file.name}: {e}")
+
+ return processed_files
+
+ async def _process_lightrag(self, new_files: List[Path]) -> List[Path]:
+ """
+ Incremental add for LightRAG pipeline (text-only).
+ Lazy imports lightrag only when needed - does NOT require raganything.
+ """
+ logger.info("Using LightRAG incremental add (text-only)...")
+
+ # Lazy import lightrag
+ try:
+ from lightrag import LightRAG
+ from lightrag.utils import EmbeddingFunc
+ except ImportError as e:
+ raise ImportError(
+ f"LightRAG dependencies not installed. "
+ f"Install with: pip install lightrag. Error: {e}"
+ ) from e
from src.services.rag.components.routing import FileTypeRouter
+ from src.services.embedding import get_embedding_client, get_embedding_config, reset_embedding_client
+ from src.services.llm import get_llm_client
- # Pre-import progress stage if needed to avoid overhead in loop
+ # Pre-import progress stage if needed
ProgressStage: Any = None
if self.progress_tracker:
from src.knowledge.progress_tracker import ProgressStage
- # Use unified LLM client from src/services/llm
+ # Setup LLM and embedding
+ llm_client = get_llm_client()
+ self.llm_cfg = llm_client.config
+ llm_model_func = llm_client.get_model_func()
+
+ reset_embedding_client()
+ embedding_cfg = get_embedding_config()
+ embedding_client = get_embedding_client()
+
+ async def unified_embed_func(texts):
+ return await embedding_client.embed(texts)
+
+ embedding_func = EmbeddingFunc(
+ embedding_dim=embedding_cfg.dim,
+ max_token_size=embedding_cfg.max_tokens,
+ func=unified_embed_func,
+ )
+
+ # Create LightRAG instance (text-only, no raganything)
+ with LightRAGLogContext(scene="knowledge_incremental"):
+ rag = LightRAG(
+ working_dir=str(self.rag_storage_dir),
+ llm_model_func=llm_model_func,
+ embedding_func=embedding_func,
+ )
+ await rag.initialize_storages()
+
+ from lightrag.kg.shared_storage import initialize_pipeline_status
+ await initialize_pipeline_status()
+
+ # Classify files
+ file_paths_str = [str(f) for f in new_files]
+ classification = FileTypeRouter.classify_files(file_paths_str)
+
+ logger.info(
+ f"File classification: {len(classification.needs_mineru)} need parsing, "
+ f"{len(classification.text_files)} text files, "
+ f"{len(classification.unsupported)} unsupported"
+ )
+
+ processed_files = []
+ total_files = len(classification.needs_mineru) + len(classification.text_files)
+ idx = 0
+
+ # For LightRAG (text-only), use basic PDF text extraction for PDFs
+ for doc_file_str in classification.needs_mineru:
+ doc_file = Path(doc_file_str)
+ idx += 1
+ try:
+ if self.progress_tracker and ProgressStage:
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_FILE,
+ f"Extracting text from {doc_file.name}",
+ current=idx,
+ total=total_files,
+ )
+
+ if not doc_file.exists():
+ logger.error(f" ✗ Failed: File missing {doc_file.name}")
+ continue
+
+ # Basic text extraction
+ content = await self._extract_text_basic(doc_file)
+ if content.strip():
+ await rag.ainsert(content)
+ processed_files.append(doc_file)
+ self._record_successful_hash(doc_file)
+ logger.info(f" ✓ Processed (LightRAG): {doc_file.name}")
+ else:
+ logger.warning(f" ⚠ No text extracted: {doc_file.name}")
+ except Exception as e:
+ logger.exception(f" ✗ Failed {doc_file.name}: {e}")
+
+ # Process text files directly
+ for doc_file_str in classification.text_files:
+ doc_file = Path(doc_file_str)
+ idx += 1
+ try:
+ if self.progress_tracker and ProgressStage:
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_FILE,
+ f"Ingesting (text) {doc_file.name}",
+ current=idx,
+ total=total_files,
+ )
+
+ if not doc_file.exists():
+ logger.error(f" ✗ Failed: File missing {doc_file.name}")
+ continue
+
+ content = await FileTypeRouter.read_text_file(str(doc_file))
+ if content.strip():
+ await rag.ainsert(content)
+ processed_files.append(doc_file)
+ self._record_successful_hash(doc_file)
+ logger.info(f" ✓ Processed (text): {doc_file.name}")
+ else:
+ logger.warning(f" ⚠ Skipped empty file: {doc_file.name}")
+ except Exception as e:
+ logger.exception(f" ✗ Failed {doc_file.name}: {e}")
+
+ for doc_file_str in classification.unsupported:
+ logger.warning(f" ⚠ Skipped unsupported file: {Path(doc_file_str).name}")
+
+ return processed_files
+
+ async def _process_raganything(self, new_files: List[Path], parser: str = "mineru") -> List[Path]:
+ """
+ Incremental add for RAGAnything pipeline (multimodal).
+ Lazy imports raganything only when needed.
+
+ Args:
+ parser: "mineru" for RAGAnything, "docling" for RAGAnything Docling
+ """
+ parser_name = "MinerU" if parser == "mineru" else "Docling"
+ logger.info(f"Using RAGAnything incremental add with {parser_name} parser...")
+
+ # Lazy import raganything
+ try:
+ # Add RAG-Anything to path if needed
+ project_root = Path(__file__).resolve().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))
+
+ from raganything import RAGAnything, RAGAnythingConfig
+ from lightrag.utils import EmbeddingFunc
+ except ImportError as e:
+ raise ImportError(
+ f"RAGAnything dependencies not installed. "
+ f"Please install raganything package. Error: {e}"
+ ) from e
+
+ from src.services.rag.components.routing import FileTypeRouter
+ from src.services.rag.utils.image_migration import (
+ cleanup_parser_output_dirs,
+ migrate_images_and_update_paths,
+ )
+ from src.services.embedding import get_embedding_client, get_embedding_config, reset_embedding_client
from src.services.llm import get_llm_client
+ # Pre-import progress stage if needed
+ ProgressStage: Any = None
+ if self.progress_tracker:
+ from src.knowledge.progress_tracker import ProgressStage
+
+ # Setup LLM and embedding
llm_client = get_llm_client()
self.llm_cfg = llm_client.config
-
- # 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()
embedding_cfg = get_embedding_config()
embedding_client = get_embedding_client()
@@ -246,16 +482,17 @@ class DocumentAdder:
func=unified_embed_func,
)
+ # Configure RAGAnything with the appropriate parser
config = RAGAnythingConfig(
working_dir=str(self.rag_storage_dir),
- parser="mineru",
+ parser=parser,
enable_image_processing=True,
enable_table_processing=True,
enable_equation_processing=True,
)
- with LightRAGLogContext(scene="knowledge_init"):
- rag = raganything_cls(
+ with LightRAGLogContext(scene="knowledge_incremental"):
+ rag = RAGAnything(
config=config,
llm_model_func=llm_model_func,
vision_model_func=vision_model_func,
@@ -264,12 +501,12 @@ class DocumentAdder:
if hasattr(rag, "_ensure_lightrag_initialized"):
await rag._ensure_lightrag_initialized()
- # Classify files by type
+ # Classify files
file_paths_str = [str(f) for f in new_files]
classification = FileTypeRouter.classify_files(file_paths_str)
logger.info(
- f"File classification: {len(classification.needs_mineru)} need MinerU, "
+ f"File classification: {len(classification.needs_mineru)} need {parser_name}, "
f"{len(classification.text_files)} text files, "
f"{len(classification.unsupported)} unsupported"
)
@@ -277,8 +514,9 @@ class DocumentAdder:
processed_files = []
total_files = len(classification.needs_mineru) + len(classification.text_files)
idx = 0
+ total_images_migrated = 0
- # Process files requiring MinerU (PDF, DOCX, images)
+ # Process files requiring parser (PDF, DOCX, images)
for doc_file_str in classification.needs_mineru:
doc_file = Path(doc_file_str)
idx += 1
@@ -286,32 +524,53 @@ class DocumentAdder:
if self.progress_tracker and ProgressStage:
self.progress_tracker.update(
ProgressStage.PROCESSING_FILE,
- f"Ingesting (MinerU) {doc_file.name}",
+ f"Ingesting ({parser_name}) {doc_file.name}",
current=idx,
total=total_files,
)
- # Verify file still exists in raw/ (it should, as we staged it)
if not doc_file.exists():
- logger.error(f" ✗ Failed: Staged file missing {doc_file.name}")
+ logger.error(f" ✗ Failed: File missing {doc_file.name}")
continue
- await asyncio.wait_for(
- rag.process_document_complete(
- file_path=str(doc_file),
- output_dir=str(self.content_list_dir),
- parse_method="auto",
- ),
- timeout=600.0,
+ # Step 1: Parse document
+ logger.info(f" Step 1/3: Parsing {doc_file.name}...")
+ content_list, doc_id = await rag.parse_document(
+ file_path=str(doc_file),
+ output_dir=str(self.content_list_dir),
+ parse_method="auto",
+ )
+
+ # Step 2: Migrate images
+ logger.info(f" Step 2/3: Migrating images...")
+ updated_content_list, num_migrated = await migrate_images_and_update_paths(
+ content_list=content_list,
+ source_base_dir=self.content_list_dir,
+ target_images_dir=self.images_dir,
+ batch_size=50,
+ )
+ total_images_migrated += num_migrated
+
+ # Save content_list
+ content_list_file = self.content_list_dir / f"{doc_file.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
+ logger.info(f" Step 3/3: Inserting into knowledge graph...")
+ await rag.insert_content_list(
+ content_list=updated_content_list,
+ file_path=str(doc_file),
+ doc_id=doc_id,
)
+
processed_files.append(doc_file)
- # Store hash on success - "Canonizing" the file
self._record_successful_hash(doc_file)
- logger.info(f" ✓ Processed (MinerU): {doc_file.name}")
+ logger.info(f" ✓ Processed ({parser_name}): {doc_file.name}")
except Exception as e:
logger.exception(f" ✗ Failed {doc_file.name}: {e}")
- # Process text files directly (fast path - no MinerU)
+ # Process text files directly
for doc_file_str in classification.text_files:
doc_file = Path(doc_file_str)
idx += 1
@@ -324,15 +583,12 @@ class DocumentAdder:
total=total_files,
)
- # Verify file still exists
if not doc_file.exists():
- logger.error(f" ✗ Failed: Staged file missing {doc_file.name}")
+ logger.error(f" ✗ Failed: File missing {doc_file.name}")
continue
- # Read text file directly
content = await FileTypeRouter.read_text_file(str(doc_file))
if content.strip():
- # Insert directly into LightRAG, bypassing MinerU
await rag.lightrag.ainsert(content)
processed_files.append(doc_file)
self._record_successful_hash(doc_file)
@@ -342,13 +598,49 @@ class DocumentAdder:
except Exception as e:
logger.exception(f" ✗ Failed {doc_file.name}: {e}")
- # Log unsupported files
for doc_file_str in classification.unsupported:
logger.warning(f" ⚠ Skipped unsupported file: {Path(doc_file_str).name}")
+ # Cleanup parser output directories
+ if total_images_migrated > 0:
+ logger.info("Cleaning up temporary parser output directories...")
+ await cleanup_parser_output_dirs(self.content_list_dir)
+
await self.fix_structure()
return processed_files
+ async def _extract_text_basic(self, file_path: Path) -> str:
+ """Basic text extraction for LightRAG (text-only pipeline)."""
+ suffix = file_path.suffix.lower()
+
+ if suffix == ".pdf":
+ try:
+ import fitz # PyMuPDF
+ doc = fitz.open(file_path)
+ texts = []
+ for page in doc:
+ texts.append(page.get_text())
+ doc.close()
+ return "\n\n".join(texts)
+ except ImportError:
+ logger.warning("PyMuPDF not installed. Cannot extract PDF text.")
+ return ""
+ except Exception as e:
+ logger.error(f"Failed to extract PDF text: {e}")
+ return ""
+ else:
+ # Try to read as text
+ try:
+ with open(file_path, "r", encoding="utf-8") as f:
+ return f.read()
+ except Exception:
+ try:
+ with open(file_path, "r", encoding="latin-1") as f:
+ return f.read()
+ except Exception as e:
+ logger.error(f"Failed to read file as text: {e}")
+ return ""
+
def _record_successful_hash(self, file_path: Path):
"""Update metadata with the hash of a successfully processed file."""
file_hash = self._get_file_hash(file_path)
@@ -452,6 +744,11 @@ class DocumentAdder:
)
def update_metadata(self, added_count: int):
+ """Update metadata after incremental add.
+
+ Note: We do NOT update rag_provider here - incremental adds must use
+ the same provider as the original initialization for consistency.
+ """
if not self.metadata_file.exists():
return
try:
@@ -460,18 +757,9 @@ class DocumentAdder:
metadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- # Update RAG provider if specified
- if self.rag_provider:
- metadata["rag_provider"] = self.rag_provider
-
- # Also save to centralized config file
- try:
- from src.services.config import get_kb_config_service
-
- kb_config_service = get_kb_config_service()
- kb_config_service.set_rag_provider(self.kb_name, self.rag_provider)
- except Exception as config_err:
- logger.warning(f"Failed to save to centralized config: {config_err}")
+ # Record the provider used (should match what's already in metadata)
+ if "rag_provider" not in metadata and self._resolved_provider:
+ metadata["rag_provider"] = self._resolved_provider
history = metadata.get("update_history", [])
history.append(
@@ -479,6 +767,7 @@ class DocumentAdder:
"timestamp": metadata["last_updated"],
"action": "incremental_add",
"count": added_count,
+ "provider": self._resolved_provider,
}
)
metadata["update_history"] = history
@@ -490,7 +779,17 @@ class DocumentAdder:
async def main():
- parser = argparse.ArgumentParser(description="Incrementally add documents to RAG KB")
+ parser = argparse.ArgumentParser(
+ description="Incrementally add documents to RAG KB",
+ epilog="""
+Example usage:
+ # Add documents to existing KB (uses provider from KB metadata)
+ python -m src.knowledge.add_documents my_kb --docs doc1.pdf doc2.txt
+
+ # Add all documents from a directory
+ python -m src.knowledge.add_documents my_kb --docs-dir ./documents/
+ """,
+ )
parser.add_argument("kb_name", help="KB Name")
parser.add_argument("--docs", nargs="+", help="Files")
parser.add_argument("--docs-dir", help="Directory")
@@ -501,10 +800,6 @@ async def main():
args = parser.parse_args()
- # Initialize dynamic paths
- project_root = Path(__file__).parent.parent.parent
- load_dynamic_imports(project_root)
-
load_dotenv()
doc_files = []
diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.py
index 76eff0b76..81bc9d7b2 100644
--- a/src/knowledge/initializer.py
+++ b/src/knowledge/initializer.py
@@ -88,6 +88,16 @@ class KnowledgeBaseInitializer:
except Exception as e:
logger.warning(f"Failed to register to config: {e}")
+ def _get_file_hash(self, file_path: Path) -> str:
+ """Calculate SHA-256 hash of a file."""
+ import hashlib
+ sha256_hash = hashlib.sha256()
+ chunk_size = 65536 # 64KB
+ with open(file_path, "rb") as f:
+ for byte_block in iter(lambda: f.read(chunk_size), b""):
+ sha256_hash.update(byte_block)
+ return sha256_hash.hexdigest()
+
def _update_metadata_with_provider(self, provider: str):
"""Update metadata.json and centralized config with the RAG provider used."""
metadata_file = self.kb_dir / "metadata.json"
@@ -101,10 +111,22 @@ class KnowledgeBaseInitializer:
metadata["rag_provider"] = provider
metadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ # Record file hashes for all successfully processed files in raw/
+ # This enables incremental add to detect duplicates
+ file_hashes = metadata.get("file_hashes", {})
+ for raw_file in self.raw_dir.glob("*"):
+ if raw_file.is_file():
+ try:
+ file_hashes[raw_file.name] = self._get_file_hash(raw_file)
+ except Exception as hash_err:
+ logger.warning(f"Failed to hash {raw_file.name}: {hash_err}")
+ metadata["file_hashes"] = file_hashes
+
with open(metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, indent=2, ensure_ascii=False, fp=f)
logger.info(f" ✓ Updated metadata with RAG provider: {provider}")
+ logger.info(f" ✓ Recorded {len(file_hashes)} file hashes for incremental add")
# Also save to centralized config file
try:
diff --git a/src/services/rag/pipelines/llamaindex.py b/src/services/rag/pipelines/llamaindex.py
index 09918ce4f..1fae7528d 100644
--- a/src/services/rag/pipelines/llamaindex.py
+++ b/src/services/rag/pipelines/llamaindex.py
@@ -292,6 +292,105 @@ class LlamaIndexPipeline:
"provider": "llamaindex",
}
+ async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ """
+ Incrementally add documents to an existing LlamaIndex KB.
+
+ If the storage directory exists, loads the existing index and inserts
+ new documents. Otherwise, creates a new index.
+
+ Args:
+ kb_name: Knowledge base name
+ file_paths: List of file paths to add
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(
+ f"Adding {len(file_paths)} documents to KB '{kb_name}' using LlamaIndex"
+ )
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ storage_dir = kb_dir / "llamaindex_storage"
+
+ try:
+ # Parse new documents
+ documents = []
+ for file_path in file_paths:
+ file_path = Path(file_path)
+ self.logger.info(f"Parsing: {file_path.name}")
+
+ # Extract text based on file type
+ if file_path.suffix.lower() == ".pdf":
+ text = self._extract_pdf_text(file_path)
+ else:
+ try:
+ with open(file_path, "r", encoding="utf-8") as f:
+ text = f.read()
+ except UnicodeDecodeError:
+ with open(file_path, "r", encoding="latin-1") as f:
+ text = f.read()
+
+ if text.strip():
+ doc = Document(
+ text=text,
+ metadata={
+ "file_name": file_path.name,
+ "file_path": str(file_path),
+ },
+ )
+ documents.append(doc)
+ self.logger.info(f"Loaded: {file_path.name} ({len(text)} chars)")
+ else:
+ self.logger.warning(f"Skipped empty document: {file_path.name}")
+
+ if not documents:
+ self.logger.warning("No valid documents to add")
+ return False
+
+ loop = asyncio.get_event_loop()
+
+ if storage_dir.exists():
+ # Load existing index and insert new documents
+ self.logger.info(f"Loading existing index from {storage_dir}...")
+
+ def load_and_insert():
+ storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
+ index = load_index_from_storage(storage_context)
+
+ # Insert new documents
+ for doc in documents:
+ index.insert(doc)
+
+ # Persist updated index
+ index.storage_context.persist(persist_dir=str(storage_dir))
+ return len(documents)
+
+ num_added = await loop.run_in_executor(None, load_and_insert)
+ self.logger.info(f"Added {num_added} documents to existing index")
+ else:
+ # Create new index (first time)
+ self.logger.info(f"Creating new index with {len(documents)} documents...")
+ storage_dir.mkdir(parents=True, exist_ok=True)
+
+ def create_index():
+ index = VectorStoreIndex.from_documents(documents, show_progress=True)
+ index.storage_context.persist(persist_dir=str(storage_dir))
+ return len(documents)
+
+ num_added = await loop.run_in_executor(None, create_index)
+ self.logger.info(f"Created new index with {num_added} documents")
+
+ self.logger.info(f"Successfully added documents to KB '{kb_name}'")
+ return True
+
+ except Exception as e:
+ self.logger.error(f"Failed to add documents: {e}")
+ import traceback
+ self.logger.error(traceback.format_exc())
+ return False
+
async def delete(self, kb_name: str) -> bool:
"""
Delete knowledge base.
diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsx
index 893d60024..ed04360a0 100644
--- a/web/app/knowledge/page.tsx
+++ b/web/app/knowledge/page.tsx
@@ -1595,60 +1595,20 @@ export default function KnowledgePage() {
</p>
<form onSubmit={handleUpload} className="space-y-4">
+ {/* Provider is LOCKED for incremental uploads - display only, no selection */}
<div>
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
- {t("RAG Provider (Optional)")}
+ {t("RAG Provider")}
</label>
- <select
- value={ragProvider}
- onChange={(e) => setRagProvider(e.target.value)}
- className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
- >
- {ragProviders.length > 0 ? (
- ragProviders.map((provider) => (
- <option key={provider.id} value={provider.id}>
- {provider.name}
- </option>
- ))
- ) : (
- <>
- <option value="llamaindex">{t("LlamaIndex")}</option>
- <option value="lightrag">{t("LightRAG")}</option>
- <option value="raganything">{t("RAG-Anything")}</option>
- </>
- )}
- </select>
- {/* Provider description */}
- <div className="mt-2 p-2.5 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600">
- <p className="text-xs text-slate-600 dark:text-slate-300">
- {(() => {
- const selectedProvider = ragProviders.find(
- (p) => p.id === ragProvider,
- );
- if (selectedProvider?.description) {
- return selectedProvider.description;
- }
- const fallbackDescriptions: Record<string, string> = {
- llamaindex:
- t("Pure vector retrieval, fastest processing speed."),
- lightrag:
- t(
- "Lightweight knowledge graph retrieval, fast processing of text documents.",
- ),
- raganything:
- t(
- "Multimodal document processing with chart and formula extraction, builds knowledge graphs.",
- ),
- };
- return (
- fallbackDescriptions[ragProvider] ||
- t("Select a RAG pipeline suitable for your document type")
- );
- })()}
- </p>
+ <div className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-600 bg-slate-100 dark:bg-slate-600 text-slate-900 dark:text-slate-100">
+ {ragProvider === "llamaindex" && t("LlamaIndex")}
+ {ragProvider === "lightrag" && t("LightRAG")}
+ {ragProvider === "raganything" && t("RAG-Anything")}
+ {ragProvider === "raganything_docling" && t("RAG-Anything (Docling)")}
+ {!["llamaindex", "lightrag", "raganything", "raganything_docling"].includes(ragProvider) && ragProvider}
</div>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1">
- {t("Leave as-is to use the KB's existing provider")}
+ {t("Keep unchanged to use this KB's existing provider")}
</p>
</div>
diff --git a/web/app/page.tsx b/web/app/page.tsx
index 6c7efd5ee..114b3004f 100644
--- a/web/app/page.tsx
+++ b/web/app/page.tsx
@@ -50,7 +50,7 @@ export default function HomePage() {
const [inputMessage, setInputMessage] = useState("");
const [kbs, setKbs] = useState<KnowledgeBase[]>([]);
- const chatEndRef = useRef<HTMLDivElement>(null);
+ const messagesContainerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [showNotebookModal, setShowNotebookModal] = useState(false);
@@ -113,8 +113,13 @@ export default function HomePage() {
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
- if (chatEndRef.current) {
- chatEndRef.current.scrollIntoView({ behavior: "smooth" });
+ if (messagesContainerRef.current) {
+ const container = messagesContainerRef.current;
+ // Use scrollTop instead of scrollIntoView to prevent page-level scrolling
+ container.scrollTo({
+ top: container.scrollHeight,
+ behavior: "smooth",
+ });
}
}, [chatState.messages]);
@@ -394,7 +399,7 @@ export default function HomePage() {
</div>
{/* Messages Area */}
- <div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
+ <div ref={messagesContainerRef} className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
{chatState.messages.map((msg, idx) => (
<div
key={idx}
@@ -497,8 +502,6 @@ export default function HomePage() {
</div>
</div>
)}
-
- <div ref={chatEndRef} />
</div>
{/* Input Area - Fixed at bottom */}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index d3504c69a..143f8563f 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -392,6 +392,7 @@
"Guided Learning": "Guided Learning",
"Manage and explore your educational content repositories.": "Manage and explore your educational content repositories.",
"RAG-Anything": "RAG-Anything",
+ "RAG-Anything (Docling)": "RAG-Anything (Docling)",
"Documents": "Documents",
"Images": "Images",
"Status": "Status",
@@ -416,6 +417,7 @@
"RAG Provider": "RAG Provider",
"RAG Provider (Optional)": "RAG Provider (Optional)",
"Leave as-is to use the KB's existing provider": "Leave as-is to use the KB's existing provider",
+ "Keep unchanged to use this KB's existing provider": "Keep unchanged to use this KB's existing provider",
"Clear progress status": "Clear progress status",
"DeepTutor Logo": "DeepTutor Logo",
"Optimizing topic...": "Optimizing topic...",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 47bdecaa0..b5ec5a210 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -392,6 +392,7 @@
"Guided Learning": "引导式学习",
"Manage and explore your educational content repositories.": "管理与探索你的教育内容仓库。",
"RAG-Anything": "RAG-Anything",
+ "RAG-Anything (Docling)": "RAG-Anything (Docling)",
"Documents": "文档",
"Images": "图片",
"Status": "状态",
@@ -416,6 +417,7 @@
"RAG Provider": "RAG 提供方",
"RAG Provider (Optional)": "RAG 提供方(可选)",
"Leave as-is to use the KB's existing provider": "保持不变以使用该知识库已有的提供方",
+ "Keep unchanged to use this KB's existing provider": "保持不变以使用该知识库已有的提供方",
"Clear progress status": "清除进度状态",
"DeepTutor Logo": "DeepTutor Logo",
"Optimizing topic...": "正在优化主题…",
diff --git a/web/next-env.d.ts b/web/next-env.d.ts
index 9edff1c7c..c4b7818fb 100644
--- a/web/next-env.d.ts
+++ b/web/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/types/routes.d.ts";
+import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.