Skip to content

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

fix: KB init & migrate, code structure

Bingxi Zhao1e9cc6b26d7b
diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml
index 2585a1f29..6ac638834 100644
--- a/.github/workflows/linting.yaml
+++ b/.github/workflows/linting.yaml
@@ -20,7 +20,7 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v6
+ uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
@@ -72,7 +72,7 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v6
+ uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 75e7ac56f..024a41fa7 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -31,11 +31,11 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: ["3.10", "3.11"]
+ python-version: ["3.10", "3.11", "3.12"]
steps:
- name: Checkout code
- uses: actions/checkout@v6
+ uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
@@ -78,6 +78,8 @@ jobs:
python -c "from src.services.config.loader import load_config_with_main; print('✅ Config loader imports OK')"
python -c "from src.services.config.unified_config import UnifiedConfigManager; print('✅ Unified config imports OK')"
python -c "from src.logging import get_logger; print('✅ Logging imports OK')"
+ python -c "from src.services.prompt import get_prompt_manager; print('✅ Prompt service imports OK')"
+ python -c "from src.services.search import web_search; print('✅ Search service imports OK')"
env:
PYTHONPATH: ${{ github.workspace }}
@@ -91,11 +93,11 @@ jobs:
strategy:
fail-fast: false
matrix:
- python-version: ["3.10", "3.11"]
+ python-version: ["3.10", "3.11", "3.12"]
steps:
- name: Checkout code
- uses: actions/checkout@v6
+ uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
@@ -155,6 +157,7 @@ jobs:
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
+ echo "| 3.12 | ${{ 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'
diff --git a/assets/releases/ver0-5-1.md b/assets/releases/ver0-5-1.md
index eaf49db74..a290ed9de 100644
--- a/assets/releases/ver0-5-1.md
+++ b/assets/releases/ver0-5-1.md
@@ -29,4 +29,3 @@ Refactored the logging system for better management:
---
**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v0.5.0...v0.5.1
-
diff --git a/scripts/check_install.py b/scripts/check_install.py
index 5680e9f46..47f63c3ed 100644
--- a/scripts/check_install.py
+++ b/scripts/check_install.py
@@ -458,4 +458,3 @@ if __name__ == "__main__":
traceback.print_exc()
sys.exit(1)
-
diff --git a/scripts/migrate_kb.py b/scripts/migrate_kb.py
index a94fe0ec1..c5a5ea7ec 100644
--- a/scripts/migrate_kb.py
+++ b/scripts/migrate_kb.py
@@ -21,11 +21,11 @@ Usage:
import argparse
import asyncio
+from datetime import datetime
import json
+from pathlib import Path
import shutil
import sys
-from datetime import datetime
-from pathlib import Path
# Add project root to path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
@@ -68,35 +68,31 @@ DEFAULT_KB_BASE_DIR = PROJECT_ROOT / "data" / "knowledge_bases"
def detect_provider(kb_path: Path) -> str | None:
"""
Detect the RAG provider type based on directory structure and valid files.
-
+
Args:
kb_path: Path to the knowledge base directory
-
+
Returns:
Provider name: "llamaindex", "lightrag", or None if not detected
"""
llamaindex_dir = kb_path / "llamaindex_storage"
lightrag_dir = kb_path / "rag_storage"
-
+
has_llamaindex = llamaindex_dir.exists() and llamaindex_dir.is_dir()
has_lightrag = lightrag_dir.exists() and lightrag_dir.is_dir()
-
+
# Check which one has valid index files
llamaindex_valid = False
lightrag_valid = False
-
+
if has_llamaindex:
# Check if LlamaIndex has required files
- llamaindex_valid = all(
- (llamaindex_dir / f).exists() for f in LLAMAINDEX_REQUIRED_FILES
- )
-
+ llamaindex_valid = all((llamaindex_dir / f).exists() for f in LLAMAINDEX_REQUIRED_FILES)
+
if has_lightrag:
# Check if LightRAG has required files
- lightrag_valid = all(
- (lightrag_dir / f).exists() for f in LIGHTRAG_REQUIRED_FILES
- )
-
+ lightrag_valid = all((lightrag_dir / f).exists() for f in LIGHTRAG_REQUIRED_FILES)
+
# Return based on which has valid files
if llamaindex_valid and lightrag_valid:
# Both valid, prefer LightRAG (more feature-rich)
@@ -118,62 +114,62 @@ def detect_provider(kb_path: Path) -> str | None:
def validate_llamaindex_files(storage_dir: Path) -> tuple[bool, list[str], list[str]]:
"""
Validate LlamaIndex storage has required files.
-
+
Args:
storage_dir: Path to llamaindex_storage directory
-
+
Returns:
Tuple of (is_valid, missing_files, found_files)
"""
missing = []
found = []
-
+
for filename in LLAMAINDEX_REQUIRED_FILES:
filepath = storage_dir / filename
if filepath.exists():
found.append(filename)
else:
missing.append(filename)
-
+
return len(missing) == 0, missing, found
def validate_lightrag_files(storage_dir: Path) -> tuple[bool, list[str], list[str]]:
"""
Validate LightRAG storage has required files.
-
+
Args:
storage_dir: Path to rag_storage directory
-
+
Returns:
Tuple of (is_valid, missing_files, found_files)
"""
missing = []
found = []
-
+
for filename in LIGHTRAG_REQUIRED_FILES:
filepath = storage_dir / filename
if filepath.exists():
found.append(filename)
else:
missing.append(filename)
-
+
# Also check optional files
optional_found = []
for filename in LIGHTRAG_OPTIONAL_FILES:
if (storage_dir / filename).exists():
optional_found.append(filename)
-
+
return len(missing) == 0, missing, found + optional_found
def validate_kb(kb_path: Path) -> dict:
"""
Validate a knowledge base directory.
-
+
Args:
kb_path: Path to the knowledge base directory
-
+
Returns:
Validation result dictionary
"""
@@ -190,18 +186,20 @@ def validate_kb(kb_path: Path) -> dict:
"has_metadata": False,
"has_numbered_items": False,
}
-
+
if not kb_path.exists():
return result
-
+
# Detect provider
provider = detect_provider(kb_path)
result["provider"] = provider
-
+
if provider is None:
- result["error"] = "No valid RAG storage found (neither llamaindex_storage/ nor rag_storage/)"
+ result["error"] = (
+ "No valid RAG storage found (neither llamaindex_storage/ nor rag_storage/)"
+ )
return result
-
+
# Validate based on provider
if provider == "llamaindex":
storage_dir = kb_path / "llamaindex_storage"
@@ -209,27 +207,24 @@ def validate_kb(kb_path: Path) -> dict:
else: # lightrag
storage_dir = kb_path / "rag_storage"
is_valid, missing, found = validate_lightrag_files(storage_dir)
-
+
result["is_valid"] = is_valid
result["missing_files"] = missing
result["found_files"] = found
-
+
# Check optional directories
content_list_dir = kb_path / "content_list"
- result["has_content_list"] = (
- content_list_dir.exists()
- and any(content_list_dir.glob("*.json"))
- )
-
+ result["has_content_list"] = content_list_dir.exists() and any(content_list_dir.glob("*.json"))
+
raw_dir = kb_path / "raw"
result["has_raw_docs"] = raw_dir.exists() and any(raw_dir.iterdir())
-
+
images_dir = kb_path / "images"
result["has_images"] = images_dir.exists() and any(images_dir.iterdir())
-
+
result["has_metadata"] = (kb_path / "metadata.json").exists()
result["has_numbered_items"] = (kb_path / "numbered_items.json").exists()
-
+
return result
@@ -238,19 +233,15 @@ def validate_kb(kb_path: Path) -> dict:
# =============================================================================
-def copy_kb_directory(
- source_path: Path,
- target_path: Path,
- verbose: bool = True
-) -> bool:
+def copy_kb_directory(source_path: Path, target_path: Path, verbose: bool = True) -> bool:
"""
Copy knowledge base directory to target location.
-
+
Args:
source_path: Source KB directory
target_path: Target KB directory
verbose: Print progress messages
-
+
Returns:
True if successful
"""
@@ -258,69 +249,66 @@ def copy_kb_directory(
if verbose:
print(f" ⚠️ Target directory already exists: {target_path}")
return False
-
+
if verbose:
print(f" Copying {source_path} -> {target_path}")
-
+
shutil.copytree(source_path, target_path)
-
+
if verbose:
- print(f" ✓ Copied successfully")
-
+ print(" ✓ Copied successfully")
+
return True
def register_kb(
- kb_name: str,
- kb_base_dir: Path,
- description: str = "",
- provider: str | None = None
+ kb_name: str, kb_base_dir: Path, description: str = "", provider: str | None = None
) -> bool:
"""
Register knowledge base in kb_config.json.
-
+
Args:
kb_name: Knowledge base name
kb_base_dir: Base directory containing kb_config.json
description: Optional description
provider: RAG provider name
-
+
Returns:
True if successful
"""
config_file = kb_base_dir / "kb_config.json"
-
+
# Load existing config
if config_file.exists():
with open(config_file, encoding="utf-8") as f:
config = json.load(f)
else:
config = {"knowledge_bases": {}}
-
+
if "knowledge_bases" not in config:
config["knowledge_bases"] = {}
-
+
# Check if already registered
if kb_name in config["knowledge_bases"]:
print(f" ⚠️ KB '{kb_name}' is already registered in kb_config.json")
return True
-
+
# Add to config
config["knowledge_bases"][kb_name] = {
"path": kb_name,
"description": description or f"Knowledge base: {kb_name}",
}
-
+
# Save config
with open(config_file, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
-
+
print(f" ✓ Registered '{kb_name}' in kb_config.json")
-
+
# Also create/update metadata.json if needed
kb_dir = kb_base_dir / kb_name
metadata_file = kb_dir / "metadata.json"
-
+
if not metadata_file.exists():
metadata = {
"name": kb_name,
@@ -332,31 +320,31 @@ def register_kb(
}
with open(metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2, ensure_ascii=False)
- print(f" ✓ Created metadata.json")
+ print(" ✓ Created metadata.json")
else:
# Update existing metadata with migration info
with open(metadata_file, encoding="utf-8") as f:
metadata = json.load(f)
-
+
if provider and not metadata.get("rag_provider"):
metadata["rag_provider"] = provider
metadata["migrated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
+
with open(metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2, ensure_ascii=False)
- print(f" ✓ Updated metadata.json")
-
+ print(" ✓ Updated metadata.json")
+
return True
async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
"""
Extract numbered items from content_list files.
-
+
Args:
kb_name: Knowledge base name
kb_base_dir: Base directory for knowledge bases
-
+
Returns:
True if successful
"""
@@ -368,24 +356,24 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
except ImportError as e:
print(f" ⚠️ Could not import extraction module: {e}")
return False
-
+
kb_dir = kb_base_dir / kb_name
content_list_dir = kb_dir / "content_list"
-
+
if not content_list_dir.exists():
- print(f" ⚠️ No content_list directory found")
+ print(" ⚠️ No content_list directory found")
return False
-
+
# Load all content list files
all_content_items = []
json_files = list(content_list_dir.glob("*.json"))
-
+
if not json_files:
- print(f" ⚠️ No JSON files found in content_list/")
+ print(" ⚠️ No JSON files found in content_list/")
return False
-
+
print(f" Loading {len(json_files)} content list files...")
-
+
for json_file in json_files:
try:
with open(json_file, encoding="utf-8") as f:
@@ -394,13 +382,13 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
all_content_items.extend(content_items)
except Exception as e:
print(f" ⚠️ Error loading {json_file.name}: {e}")
-
+
if not all_content_items:
- print(f" ⚠️ No content items found")
+ print(" ⚠️ No content items found")
return False
-
+
print(f" Extracting numbered items from {len(all_content_items)} content items...")
-
+
try:
llm_client = get_llm_client()
items = await extract_numbered_items_with_llm_async(
@@ -408,7 +396,7 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
api_key=llm_client.config.api_key,
base_url=llm_client.config.base_url,
)
-
+
if items:
output_file = kb_dir / "numbered_items.json"
with open(output_file, "w", encoding="utf-8") as f:
@@ -416,9 +404,9 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
print(f" ✓ Extracted {len(items)} numbered items")
return True
else:
- print(f" ⚠️ No numbered items extracted")
+ print(" ⚠️ No numbered items extracted")
return False
-
+
except Exception as e:
print(f" ✗ Extraction failed: {e}")
return False
@@ -427,11 +415,11 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
async def test_kb_search(kb_name: str, query: str = "What is this knowledge base about?") -> bool:
"""
Test knowledge base with a simple search query.
-
+
Args:
kb_name: Knowledge base name
query: Test query
-
+
Returns:
True if search succeeded
"""
@@ -440,26 +428,26 @@ async def test_kb_search(kb_name: str, query: str = "What is this knowledge base
except ImportError as e:
print(f" ⚠️ Could not import rag_tool: {e}")
return False
-
+
print(f" Running test query: '{query[:50]}...'")
-
+
try:
result = await rag_search(
query=query,
kb_name=kb_name,
mode="naive", # Use simplest mode for testing
)
-
+
if result and result.get("answer"):
answer_preview = result["answer"][:200]
- print(f" ✓ Search successful!")
+ print(" ✓ Search successful!")
print(f" Provider: {result.get('provider', 'unknown')}")
print(f" Answer preview: {answer_preview}...")
return True
else:
- print(f" ⚠️ Search returned empty result")
+ print(" ⚠️ Search returned empty result")
return False
-
+
except Exception as e:
print(f" ✗ Search failed: {e}")
return False
@@ -476,7 +464,7 @@ async def migrate_kb(
) -> bool:
"""
Migrate a knowledge base to DeepTutor.
-
+
Args:
source_path: Path to source knowledge base
target_base_dir: Target base directory (default: data/knowledge_bases)
@@ -485,74 +473,74 @@ async def migrate_kb(
extract_items: Extract numbered items if content_list exists
validate_only: Only validate, don't migrate
force: Overwrite existing KB if exists
-
+
Returns:
True if successful
"""
source = Path(source_path).resolve()
target_base = Path(target_base_dir) if target_base_dir else DEFAULT_KB_BASE_DIR
target_base = target_base.resolve()
-
+
# Determine KB name
if kb_name is None:
kb_name = source.name
-
+
print("=" * 60)
- print(f"Knowledge Base Migration")
+ print("Knowledge Base Migration")
print("=" * 60)
print(f"Source: {source}")
print(f"Target: {target_base / kb_name}")
print()
-
+
# Step 1: Validate source KB
print("Step 1: Validating source knowledge base...")
validation = validate_kb(source)
-
+
if not validation["exists"]:
print(f" ✗ Source directory does not exist: {source}")
return False
-
+
if not validation["is_valid"]:
- print(f" ✗ Validation failed!")
+ print(" ✗ Validation failed!")
if validation.get("error"):
print(f" Error: {validation['error']}")
if validation["missing_files"]:
print(f" Missing files: {', '.join(validation['missing_files'])}")
return False
-
- print(f" ✓ Validation passed")
+
+ print(" ✓ Validation passed")
print(f" Provider: {validation['provider']}")
print(f" Found files: {', '.join(validation['found_files'][:5])}...")
print(f" Has content_list: {'Yes' if validation['has_content_list'] else 'No'}")
print(f" Has raw docs: {'Yes' if validation['has_raw_docs'] else 'No'}")
print(f" Has images: {'Yes' if validation['has_images'] else 'No'}")
print()
-
+
if validate_only:
print("Validation-only mode. Exiting.")
return True
-
+
# Step 2: Copy to target
print("Step 2: Copying knowledge base...")
target_path = target_base / kb_name
-
+
if target_path.exists():
if force:
- print(f" Removing existing directory (--force)...")
+ print(" Removing existing directory (--force)...")
shutil.rmtree(target_path)
elif source.resolve() == target_path.resolve():
- print(f" Source and target are the same. Skipping copy.")
+ print(" Source and target are the same. Skipping copy.")
else:
print(f" ✗ Target directory already exists: {target_path}")
- print(f" Use --force to overwrite or --name to specify a different name")
+ print(" Use --force to overwrite or --name to specify a different name")
return False
-
+
if source.resolve() != target_path.resolve():
success = copy_kb_directory(source, target_path)
if not success:
return False
print()
-
+
# Step 3: Register in kb_config.json
print("Step 3: Registering knowledge base...")
register_kb(
@@ -562,7 +550,7 @@ async def migrate_kb(
provider=validation["provider"],
)
print()
-
+
# Step 4: Extract numbered items (optional)
if extract_items and validation["has_content_list"]:
print("Step 4: Extracting numbered items...")
@@ -571,18 +559,18 @@ async def migrate_kb(
elif extract_items:
print("Step 4: Skipping numbered items extraction (no content_list)")
print()
-
+
# Step 5: Test search (optional)
if run_test:
print("Step 5: Testing knowledge base...")
await test_kb_search(kb_name)
print()
-
+
print("=" * 60)
- print(f"✓ Migration complete!")
+ print("✓ Migration complete!")
print(f" Knowledge base '{kb_name}' is now available in DeepTutor.")
print("=" * 60)
-
+
return True
@@ -599,65 +587,54 @@ def main():
Examples:
# Migrate a knowledge base
python scripts/migrate_kb.py /path/to/my_kb
-
+
# Migrate with custom name
python scripts/migrate_kb.py /path/to/kb --name my_textbook
-
+
# Migrate and run test query
python scripts/migrate_kb.py /path/to/kb --test
-
+
# Migrate and extract numbered items
python scripts/migrate_kb.py /path/to/kb --extract-items
-
+
# Validate only (don't migrate)
python scripts/migrate_kb.py /path/to/kb --validate-only
-
+
# Force overwrite existing KB
python scripts/migrate_kb.py /path/to/kb --force
-"""
- )
-
- parser.add_argument(
- "source",
- help="Path to source knowledge base directory"
- )
-
- parser.add_argument(
- "--name",
- help="Name for the migrated knowledge base (default: source directory name)"
+""",
)
-
+
+ parser.add_argument("source", help="Path to source knowledge base directory")
+
parser.add_argument(
- "--target-dir",
- help=f"Target base directory (default: {DEFAULT_KB_BASE_DIR})"
+ "--name", help="Name for the migrated knowledge base (default: source directory name)"
)
-
+
parser.add_argument(
- "--test",
- action="store_true",
- help="Run a test query after migration"
+ "--target-dir", help=f"Target base directory (default: {DEFAULT_KB_BASE_DIR})"
)
-
+
+ parser.add_argument("--test", action="store_true", help="Run a test query after migration")
+
parser.add_argument(
"--extract-items",
action="store_true",
- help="Extract numbered items from content_list (requires LLM API)"
+ help="Extract numbered items from content_list (requires LLM API)",
)
-
+
parser.add_argument(
"--validate-only",
action="store_true",
- help="Only validate the knowledge base, don't migrate"
+ help="Only validate the knowledge base, don't migrate",
)
-
+
parser.add_argument(
- "--force",
- action="store_true",
- help="Overwrite existing knowledge base if exists"
+ "--force", action="store_true", help="Overwrite existing knowledge base if exists"
)
-
+
args = parser.parse_args()
-
+
# Run migration
success = asyncio.run(
migrate_kb(
@@ -670,10 +647,9 @@ Examples:
force=args.force,
)
)
-
+
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
-
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index b58173a56..ba200af77 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -415,8 +415,8 @@ class KnowledgeBaseManager:
if metadata_file.exists():
try:
with open(metadata_file, encoding="utf-8") as f:
- metadata = json.load(f)
- provider = metadata.get("rag_provider") or "raganything"
+ kb_meta = json.load(f)
+ provider = kb_meta.get("rag_provider") or "raganything"
except Exception:
pass
diff --git a/src/knowledge/start_kb.py b/src/knowledge/start_kb.py
index 70e2c1340..fe68a429b 100644
--- a/src/knowledge/start_kb.py
+++ b/src/knowledge/start_kb.py
@@ -15,11 +15,11 @@ try:
from .config import KNOWLEDGE_BASES_DIR, get_env_config, setup_paths
setup_paths()
+ from src.services.rag.components.routing import FileTypeRouter
+
from .extract_numbered_items import process_content_list
from .initializer import KnowledgeBaseInitializer
from .manager import KnowledgeBaseManager
-
- from src.services.rag.components.routing import FileTypeRouter
except ImportError:
# If relative import fails, means this file is run directly
# Add parent directory to path
diff --git a/src/logging/__init__.py b/src/logging/__init__.py
index fac531675..636d46342 100644
--- a/src/logging/__init__.py
+++ b/src/logging/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Unified Logging System for DeepTutor
=====================================
diff --git a/src/logging/adapters/__init__.py b/src/logging/adapters/__init__.py
index c18bf5ad0..17eaf860b 100644
--- a/src/logging/adapters/__init__.py
+++ b/src/logging/adapters/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Log Adapters
============
diff --git a/src/logging/adapters/lightrag.py b/src/logging/adapters/lightrag.py
index 6e59c2dd3..2e076e3c1 100644
--- a/src/logging/adapters/lightrag.py
+++ b/src/logging/adapters/lightrag.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
LightRAG Log Forwarder
======================
@@ -61,9 +62,10 @@ def get_lightrag_forwarding_config() -> dict:
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
+ from ..config import get_global_log_level
+
project_root = Path(__file__).resolve().parent.parent.parent.parent
config = load_config_with_main("solve_config.yaml", project_root)
logging_config = config.get("logging", {})
diff --git a/src/logging/adapters/llamaindex.py b/src/logging/adapters/llamaindex.py
index e9173c960..d21894020 100644
--- a/src/logging/adapters/llamaindex.py
+++ b/src/logging/adapters/llamaindex.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
LlamaIndex Log Forwarder
========================
diff --git a/src/logging/config.py b/src/logging/config.py
index f41ca2b51..150a40af0 100644
--- a/src/logging/config.py
+++ b/src/logging/config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Logging Configuration
=====================
diff --git a/src/logging/handlers/__init__.py b/src/logging/handlers/__init__.py
index 91d2128e2..be14785d1 100644
--- a/src/logging/handlers/__init__.py
+++ b/src/logging/handlers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Log Handlers
============
diff --git a/src/logging/handlers/file.py b/src/logging/handlers/file.py
index c7985d3bc..b579ac641 100644
--- a/src/logging/handlers/file.py
+++ b/src/logging/handlers/file.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
File Log Handlers
=================
diff --git a/src/logging/logger.py b/src/logging/logger.py
index f1b0787f7..1dab05f6f 100644
--- a/src/logging/logger.py
+++ b/src/logging/logger.py
@@ -688,7 +688,14 @@ def get_logger(
effective_level = "DEBUG"
log_dir_key = str(log_dir) if log_dir is not None else None
- cache_key = (name, effective_level, console_output, file_output, log_dir_key, effective_service_prefix)
+ 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(
diff --git a/src/logging/stats/__init__.py b/src/logging/stats/__init__.py
index dcc98c961..c23c0b1d5 100644
--- a/src/logging/stats/__init__.py
+++ b/src/logging/stats/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Statistics Tracking
===================
diff --git a/src/services/__init__.py b/src/services/__init__.py
index 46700494e..90f09d877 100644
--- a/src/services/__init__.py
+++ b/src/services/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Services Layer
==============
diff --git a/src/services/config/__init__.py b/src/services/config/__init__.py
index 9f7863906..ee927509b 100644
--- a/src/services/config/__init__.py
+++ b/src/services/config/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Configuration Service
=====================
diff --git a/src/services/config/knowledge_base_config.py b/src/services/config/knowledge_base_config.py
index 95f5713e1..2f5a0bc0b 100644
--- a/src/services/config/knowledge_base_config.py
+++ b/src/services/config/knowledge_base_config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Knowledge Base Configuration Service
=====================================
diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.py
index 44e2f23cb..bd153753d 100644
--- a/src/services/config/unified_config.py
+++ b/src/services/config/unified_config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Unified Configuration Manager
=============================
diff --git a/src/services/embedding/__init__.py b/src/services/embedding/__init__.py
index 8e393cb45..b3705a609 100644
--- a/src/services/embedding/__init__.py
+++ b/src/services/embedding/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Embedding Service
=================
diff --git a/src/services/embedding/adapters/__init__.py b/src/services/embedding/adapters/__init__.py
index 8289c56f1..6a537ad84 100644
--- a/src/services/embedding/adapters/__init__.py
+++ b/src/services/embedding/adapters/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Adapters Package
================
diff --git a/src/services/embedding/adapters/base.py b/src/services/embedding/adapters/base.py
index 23ce0b4d4..158c4dbda 100644
--- a/src/services/embedding/adapters/base.py
+++ b/src/services/embedding/adapters/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Embedding Adapter
=======================
diff --git a/src/services/embedding/adapters/cohere.py b/src/services/embedding/adapters/cohere.py
index 8753fe7a9..d6fe06fcb 100644
--- a/src/services/embedding/adapters/cohere.py
+++ b/src/services/embedding/adapters/cohere.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""Cohere Embedding Adapter for v1 and v2 API."""
import logging
diff --git a/src/services/embedding/adapters/jina.py b/src/services/embedding/adapters/jina.py
index ed87c1df4..bc1d505c0 100644
--- a/src/services/embedding/adapters/jina.py
+++ b/src/services/embedding/adapters/jina.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""Jina AI embedding adapter with task-aware embeddings and late chunking."""
import logging
diff --git a/src/services/embedding/adapters/ollama.py b/src/services/embedding/adapters/ollama.py
index 372464d3c..3f69d27d6 100644
--- a/src/services/embedding/adapters/ollama.py
+++ b/src/services/embedding/adapters/ollama.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""Ollama Embedding Adapter for local embeddings."""
import logging
diff --git a/src/services/embedding/adapters/openai_compatible.py b/src/services/embedding/adapters/openai_compatible.py
index 79051c444..345ca423f 100644
--- a/src/services/embedding/adapters/openai_compatible.py
+++ b/src/services/embedding/adapters/openai_compatible.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""OpenAI-compatible embedding adapter for OpenAI, Azure, HuggingFace, LM Studio, etc."""
import logging
diff --git a/src/services/embedding/client.py b/src/services/embedding/client.py
index ca1c7c4f1..e42383ef7 100644
--- a/src/services/embedding/client.py
+++ b/src/services/embedding/client.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Embedding Client
================
diff --git a/src/services/embedding/config.py b/src/services/embedding/config.py
index 36af8827b..d337cbcdc 100644
--- a/src/services/embedding/config.py
+++ b/src/services/embedding/config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Embedding Configuration
=======================
diff --git a/src/services/embedding/provider.py b/src/services/embedding/provider.py
index 84e7967ee..224e699a6 100644
--- a/src/services/embedding/provider.py
+++ b/src/services/embedding/provider.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Embedding Provider Manager
===========================
diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.py
index 0beb248ca..fca3d1ccd 100644
--- a/src/services/llm/__init__.py
+++ b/src/services/llm/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Service
===========
diff --git a/src/services/llm/capabilities.py b/src/services/llm/capabilities.py
index f612395ba..a469f9d89 100644
--- a/src/services/llm/capabilities.py
+++ b/src/services/llm/capabilities.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Provider Capabilities
=====================
diff --git a/src/services/llm/client.py b/src/services/llm/client.py
index 941dd1541..472685b1e 100644
--- a/src/services/llm/client.py
+++ b/src/services/llm/client.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Client
==========
diff --git a/src/services/llm/cloud_provider.py b/src/services/llm/cloud_provider.py
index 8f1257a33..352582588 100644
--- a/src/services/llm/cloud_provider.py
+++ b/src/services/llm/cloud_provider.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Cloud LLM Provider
==================
diff --git a/src/services/llm/error_mapping.py b/src/services/llm/error_mapping.py
index 05dbc7e66..a42fcb088 100644
--- a/src/services/llm/error_mapping.py
+++ b/src/services/llm/error_mapping.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Error Mapping - Map provider-specific errors to unified exceptions.
"""
diff --git a/src/services/llm/exceptions.py b/src/services/llm/exceptions.py
index d10975b26..bb85dc12d 100644
--- a/src/services/llm/exceptions.py
+++ b/src/services/llm/exceptions.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Service Exceptions
======================
diff --git a/src/services/llm/factory.py b/src/services/llm/factory.py
index 875fa0656..417419cf3 100644
--- a/src/services/llm/factory.py
+++ b/src/services/llm/factory.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Factory - Central Hub for LLM Calls
=======================================
diff --git a/src/services/llm/local_provider.py b/src/services/llm/local_provider.py
index 43147245d..f921adcb0 100644
--- a/src/services/llm/local_provider.py
+++ b/src/services/llm/local_provider.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Local LLM Provider
==================
diff --git a/src/services/llm/providers/anthropic.py b/src/services/llm/providers/anthropic.py
index f80aea73c..810e01cda 100644
--- a/src/services/llm/providers/anthropic.py
+++ b/src/services/llm/providers/anthropic.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import anthropic
from ..registry import register_provider
diff --git a/src/services/llm/providers/base_provider.py b/src/services/llm/providers/base_provider.py
index 60686a743..f2b7355d9 100644
--- a/src/services/llm/providers/base_provider.py
+++ b/src/services/llm/providers/base_provider.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base LLM Provider - Unified interface and configuration.
"""
diff --git a/src/services/llm/providers/open_ai.py b/src/services/llm/providers/open_ai.py
index 6dcfa7aaa..3c4c9c661 100644
--- a/src/services/llm/providers/open_ai.py
+++ b/src/services/llm/providers/open_ai.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
import os
import httpx
diff --git a/src/services/llm/registry.py b/src/services/llm/registry.py
index fa58b7d9d..b6b137179 100644
--- a/src/services/llm/registry.py
+++ b/src/services/llm/registry.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Provider Registry
====================
diff --git a/src/services/llm/telemetry.py b/src/services/llm/telemetry.py
index ee9f72d8c..cbadd2d9e 100644
--- a/src/services/llm/telemetry.py
+++ b/src/services/llm/telemetry.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Telemetry
=============
diff --git a/src/services/llm/types.py b/src/services/llm/types.py
index d7e8c92cb..88c62401e 100644
--- a/src/services/llm/types.py
+++ b/src/services/llm/types.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from typing import Any, AsyncGenerator, Dict, Optional
from pydantic import BaseModel, Field
diff --git a/src/services/llm/utils.py b/src/services/llm/utils.py
index b0eec0ec4..859e18a7e 100644
--- a/src/services/llm/utils.py
+++ b/src/services/llm/utils.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Utilities
=============
diff --git a/src/services/prompt/__init__.py b/src/services/prompt/__init__.py
index 6e500560f..90298670a 100644
--- a/src/services/prompt/__init__.py
+++ b/src/services/prompt/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Prompt Service
==============
diff --git a/src/services/prompt/manager.py b/src/services/prompt/manager.py
index ea20b4017..f99da2d16 100644
--- a/src/services/prompt/manager.py
+++ b/src/services/prompt/manager.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Unified Prompt Manager - Single source of truth for all prompt loading.
Supports multi-language, caching, and language fallbacks.
diff --git a/src/services/rag/__init__.py b/src/services/rag/__init__.py
index 740ede818..7a0d809f4 100644
--- a/src/services/rag/__init__.py
+++ b/src/services/rag/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Service
===========
diff --git a/src/services/rag/components/__init__.py b/src/services/rag/components/__init__.py
index aa9ef36b5..cd486aab0 100644
--- a/src/services/rag/components/__init__.py
+++ b/src/services/rag/components/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Components
==============
diff --git a/src/services/rag/components/base.py b/src/services/rag/components/base.py
index d3d63922d..daf842664 100644
--- a/src/services/rag/components/base.py
+++ b/src/services/rag/components/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Component
==============
diff --git a/src/services/rag/components/chunkers/__init__.py b/src/services/rag/components/chunkers/__init__.py
index 0d6c04ebd..a7bc8c9a7 100644
--- a/src/services/rag/components/chunkers/__init__.py
+++ b/src/services/rag/components/chunkers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Document Chunkers
=================
diff --git a/src/services/rag/components/chunkers/base.py b/src/services/rag/components/chunkers/base.py
index 06e0e4ca9..03e9a4cdc 100644
--- a/src/services/rag/components/chunkers/base.py
+++ b/src/services/rag/components/chunkers/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Chunker
============
diff --git a/src/services/rag/components/chunkers/fixed.py b/src/services/rag/components/chunkers/fixed.py
index 441de453e..4e83b6e95 100644
--- a/src/services/rag/components/chunkers/fixed.py
+++ b/src/services/rag/components/chunkers/fixed.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Fixed Size Chunker
==================
diff --git a/src/services/rag/components/chunkers/numbered_item.py b/src/services/rag/components/chunkers/numbered_item.py
index 32af2e6b0..dcc8811bc 100644
--- a/src/services/rag/components/chunkers/numbered_item.py
+++ b/src/services/rag/components/chunkers/numbered_item.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Numbered Item Extractor
=======================
diff --git a/src/services/rag/components/chunkers/semantic.py b/src/services/rag/components/chunkers/semantic.py
index ae77d8924..cb869e45e 100644
--- a/src/services/rag/components/chunkers/semantic.py
+++ b/src/services/rag/components/chunkers/semantic.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Semantic Chunker
================
diff --git a/src/services/rag/components/embedders/__init__.py b/src/services/rag/components/embedders/__init__.py
index 0102d8061..124232c4e 100644
--- a/src/services/rag/components/embedders/__init__.py
+++ b/src/services/rag/components/embedders/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Document Embedders
==================
diff --git a/src/services/rag/components/embedders/base.py b/src/services/rag/components/embedders/base.py
index 9eff02fee..07f5228c0 100644
--- a/src/services/rag/components/embedders/base.py
+++ b/src/services/rag/components/embedders/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Embedder
=============
diff --git a/src/services/rag/components/embedders/openai.py b/src/services/rag/components/embedders/openai.py
index ca1aa1379..30cc01287 100644
--- a/src/services/rag/components/embedders/openai.py
+++ b/src/services/rag/components/embedders/openai.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
OpenAI Embedder
===============
diff --git a/src/services/rag/components/indexers/__init__.py b/src/services/rag/components/indexers/__init__.py
index 10fc3c2ca..c4b498881 100644
--- a/src/services/rag/components/indexers/__init__.py
+++ b/src/services/rag/components/indexers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Document Indexers
=================
diff --git a/src/services/rag/components/indexers/base.py b/src/services/rag/components/indexers/base.py
index ee61725e7..1470ce4ba 100644
--- a/src/services/rag/components/indexers/base.py
+++ b/src/services/rag/components/indexers/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Indexer
============
diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.py
index 9c56bc5dc..03175b2b4 100644
--- a/src/services/rag/components/indexers/graph.py
+++ b/src/services/rag/components/indexers/graph.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Graph Indexer
=============
diff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.py
index 2a87a505e..9d4011d24 100644
--- a/src/services/rag/components/indexers/lightrag.py
+++ b/src/services/rag/components/indexers/lightrag.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LightRAG Indexer
================
diff --git a/src/services/rag/components/indexers/vector.py b/src/services/rag/components/indexers/vector.py
index 551b63ce5..790ff5bf5 100644
--- a/src/services/rag/components/indexers/vector.py
+++ b/src/services/rag/components/indexers/vector.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Vector Indexer
==============
diff --git a/src/services/rag/components/parsers/__init__.py b/src/services/rag/components/parsers/__init__.py
index 9b50b2f43..d5c731935 100644
--- a/src/services/rag/components/parsers/__init__.py
+++ b/src/services/rag/components/parsers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Document Parsers
================
diff --git a/src/services/rag/components/parsers/base.py b/src/services/rag/components/parsers/base.py
index 026f43d15..e1385261b 100644
--- a/src/services/rag/components/parsers/base.py
+++ b/src/services/rag/components/parsers/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Parser
===========
diff --git a/src/services/rag/components/parsers/markdown.py b/src/services/rag/components/parsers/markdown.py
index 790768371..ca8590eeb 100644
--- a/src/services/rag/components/parsers/markdown.py
+++ b/src/services/rag/components/parsers/markdown.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Markdown Parser
===============
diff --git a/src/services/rag/components/parsers/pdf.py b/src/services/rag/components/parsers/pdf.py
index 009b77149..c39d99a14 100644
--- a/src/services/rag/components/parsers/pdf.py
+++ b/src/services/rag/components/parsers/pdf.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
PDF Parser
==========
diff --git a/src/services/rag/components/parsers/text.py b/src/services/rag/components/parsers/text.py
index 6d8fbaac7..decffabbe 100644
--- a/src/services/rag/components/parsers/text.py
+++ b/src/services/rag/components/parsers/text.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Text Parser
===========
diff --git a/src/services/rag/components/retrievers/__init__.py b/src/services/rag/components/retrievers/__init__.py
index 9b358f38a..a2cea44f7 100644
--- a/src/services/rag/components/retrievers/__init__.py
+++ b/src/services/rag/components/retrievers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Document Retrievers
===================
diff --git a/src/services/rag/components/retrievers/base.py b/src/services/rag/components/retrievers/base.py
index c3f0cf7fc..79d3b2a1f 100644
--- a/src/services/rag/components/retrievers/base.py
+++ b/src/services/rag/components/retrievers/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Base Retriever
==============
diff --git a/src/services/rag/components/retrievers/dense.py b/src/services/rag/components/retrievers/dense.py
index bfbeb56ce..36e8b4d04 100644
--- a/src/services/rag/components/retrievers/dense.py
+++ b/src/services/rag/components/retrievers/dense.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Dense Retriever
===============
diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.py
index 8c1e3137f..7a054d281 100644
--- a/src/services/rag/components/retrievers/hybrid.py
+++ b/src/services/rag/components/retrievers/hybrid.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Hybrid Retriever
================
diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.py
index 334f24861..a07731f22 100644
--- a/src/services/rag/components/retrievers/lightrag.py
+++ b/src/services/rag/components/retrievers/lightrag.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LightRAG Retriever
==================
diff --git a/src/services/rag/components/routing.py b/src/services/rag/components/routing.py
index db628dde7..a25edfa23 100644
--- a/src/services/rag/components/routing.py
+++ b/src/services/rag/components/routing.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
File Type Router
================
@@ -310,10 +311,7 @@ class FileTypeRouter:
elif provider == "raganything":
# RAGAnything: PDF + Word + Images + all text files (full multimodal via MinerU)
return (
- cls.MINERU_EXTENSIONS
- | cls.DOCX_EXTENSIONS
- | cls.IMAGE_EXTENSIONS
- | text_extensions
+ cls.MINERU_EXTENSIONS | cls.DOCX_EXTENSIONS | cls.IMAGE_EXTENSIONS | text_extensions
)
else:
diff --git a/src/services/rag/factory.py b/src/services/rag/factory.py
index 0516bf952..8b47044a8 100644
--- a/src/services/rag/factory.py
+++ b/src/services/rag/factory.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Pipeline Factory
================
@@ -6,6 +7,7 @@ Factory for creating and managing RAG pipelines.
"""
from typing import Callable, Dict, List, Optional
+import warnings
from .pipelines import lightrag, llamaindex
from .pipelines.raganything import RAGAnythingPipeline
@@ -119,8 +121,6 @@ def get_plugin(name: str) -> Dict[str, Callable]:
Get a plugin by name (maps to pipeline API).
"""
- import warnings
-
warnings.warn(
"get_plugin() is deprecated, use get_pipeline() instead",
DeprecationWarning,
@@ -139,8 +139,6 @@ def list_plugins() -> List[Dict[str, str]]:
"""
DEPRECATED: Use list_pipelines() instead.
"""
- import warnings
-
warnings.warn(
"list_plugins() is deprecated, use list_pipelines() instead",
DeprecationWarning,
@@ -153,8 +151,6 @@ def has_plugin(name: str) -> bool:
"""
DEPRECATED: Use has_pipeline() instead.
"""
- import warnings
-
warnings.warn(
"has_plugin() is deprecated, use has_pipeline() instead",
DeprecationWarning,
diff --git a/src/services/rag/pipeline.py b/src/services/rag/pipeline.py
index 97ba6363a..926d14f66 100644
--- a/src/services/rag/pipeline.py
+++ b/src/services/rag/pipeline.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Pipeline
============
diff --git a/src/services/rag/pipelines/__init__.py b/src/services/rag/pipelines/__init__.py
index 7274f4492..3f0f1a07c 100644
--- a/src/services/rag/pipelines/__init__.py
+++ b/src/services/rag/pipelines/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Pre-configured Pipelines
========================
diff --git a/src/services/rag/pipelines/academic.py b/src/services/rag/pipelines/academic.py
index c5c847059..414b85356 100644
--- a/src/services/rag/pipelines/academic.py
+++ b/src/services/rag/pipelines/academic.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Academic Pipeline
=================
diff --git a/src/services/rag/pipelines/lightrag.py b/src/services/rag/pipelines/lightrag.py
index 88cfd4420..08e1154c1 100644
--- a/src/services/rag/pipelines/lightrag.py
+++ b/src/services/rag/pipelines/lightrag.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LightRAG Pipeline
=================
diff --git a/src/services/rag/pipelines/llamaindex.py b/src/services/rag/pipelines/llamaindex.py
index eb46dbff7..09918ce4f 100644
--- a/src/services/rag/pipelines/llamaindex.py
+++ b/src/services/rag/pipelines/llamaindex.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LlamaIndex Pipeline
===================
diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.py
index 38dd2363c..85478b8f9 100644
--- a/src/services/rag/pipelines/raganything.py
+++ b/src/services/rag/pipelines/raganything.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAGAnything Pipeline
====================
diff --git a/src/services/rag/pipelines/raganything_docling.py b/src/services/rag/pipelines/raganything_docling.py
index 306534d5f..f40a1890f 100644
--- a/src/services/rag/pipelines/raganything_docling.py
+++ b/src/services/rag/pipelines/raganything_docling.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAGAnything Docling Pipeline
============================
@@ -10,13 +11,13 @@ from pathlib import Path
import sys
from typing import Any, Dict, List, Optional
+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
-from src.logging import get_logger
-from src.logging.adapters import LightRAGLogContext
-
class RAGAnythingDoclingPipeline:
"""
@@ -157,7 +158,9 @@ class RAGAnythingDoclingPipeline:
migrate_images_and_update_paths,
)
- self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files (Docling parser)")
+ 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"
@@ -186,12 +189,10 @@ class RAGAnythingDoclingPipeline:
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}"
- )
+ 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...")
+ 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),
@@ -199,7 +200,7 @@ class RAGAnythingDoclingPipeline:
)
# Step 2: Migrate images and update paths
- self.logger.info(f" Step 2/3: Migrating images to canonical location...")
+ 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,
@@ -214,7 +215,7 @@ class RAGAnythingDoclingPipeline:
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...")
+ 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,
@@ -365,4 +366,3 @@ class RAGAnythingDoclingPipeline:
return True
return False
-
diff --git a/src/services/rag/service.py b/src/services/rag/service.py
index 9b66540d0..15d229c84 100644
--- a/src/services/rag/service.py
+++ b/src/services/rag/service.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Service
===========
@@ -5,12 +6,16 @@ RAG Service
Unified RAG service providing a single entry point for all RAG operations.
"""
+import json
import os
from pathlib import Path
+import shutil
from typing import Any, Dict, List, Optional
from src.logging import get_logger
+from .factory import get_pipeline, has_pipeline, list_pipelines
+
# Default knowledge base directory
DEFAULT_KB_BASE_DIR = str(
Path(__file__).resolve().parent.parent.parent.parent / "data" / "knowledge_bases"
@@ -59,8 +64,6 @@ class RAGService:
def _get_pipeline(self):
"""Get or create pipeline instance."""
if self._pipeline is None:
- from .factory import get_pipeline
-
self._pipeline = get_pipeline(self.provider, kb_base_dir=self.kb_base_dir)
return self._pipeline
@@ -117,8 +120,6 @@ class RAGService:
)
# Get pipeline for the specific provider
- from .factory import get_pipeline
-
pipeline = get_pipeline(provider, kb_base_dir=self.kb_base_dir)
result = await pipeline.search(query=query, kb_name=kb_name, mode=mode, **kwargs)
@@ -149,8 +150,6 @@ class RAGService:
Provider name (e.g., 'llamaindex', 'lightrag', 'raganything')
"""
try:
- import json
-
metadata_file = Path(self.kb_base_dir) / kb_name / "metadata.json"
if metadata_file.exists():
@@ -192,8 +191,6 @@ class RAGService:
return await pipeline.delete(kb_name=kb_name)
# Fallback: delete directory manually
- import shutil
-
kb_dir = Path(self.kb_base_dir) / kb_name
if kb_dir.exists():
shutil.rmtree(kb_dir)
@@ -214,8 +211,6 @@ class RAGService:
for p in providers:
print(f"{p['id']}: {p['description']}")
"""
- from .factory import list_pipelines
-
return list_pipelines()
@staticmethod
@@ -239,6 +234,4 @@ class RAGService:
Returns:
True if provider exists
"""
- from .factory import has_pipeline
-
return has_pipeline(name)
diff --git a/src/services/rag/types.py b/src/services/rag/types.py
index 5ce1bb088..fb1ca59b7 100644
--- a/src/services/rag/types.py
+++ b/src/services/rag/types.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Types
=========
diff --git a/src/services/rag/utils/__init__.py b/src/services/rag/utils/__init__.py
index 694b99d5c..11c268641 100644
--- a/src/services/rag/utils/__init__.py
+++ b/src/services/rag/utils/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
RAG Utilities
=============
@@ -14,4 +15,3 @@ __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
index 2785aa207..5934e1f09 100644
--- a/src/services/rag/utils/image_migration.py
+++ b/src/services/rag/utils/image_migration.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Image Migration Utilities
=========================
@@ -13,10 +14,9 @@ This is needed because:
"""
import asyncio
-import shutil
from pathlib import Path
+import shutil
from typing import Any, Dict, List, Tuple
-from concurrent.futures import ThreadPoolExecutor
from src.logging import get_logger
@@ -34,60 +34,58 @@ async def migrate_images_and_update_paths(
) -> 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
- )
+ 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
@@ -99,30 +97,25 @@ async def _process_image_batch(
) -> 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
- ]
-
+ 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):
@@ -131,7 +124,7 @@ async def _process_image_batch(
old_path, new_path = result
if new_path:
path_updates[old_path] = new_path
-
+
return path_updates
@@ -142,12 +135,12 @@ async def _migrate_single_image(
) -> 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
"""
@@ -156,22 +149,22 @@ async def _migrate_single_image(
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
@@ -180,19 +173,14 @@ async def _migrate_single_image(
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)
- )
-
+ 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)
@@ -204,38 +192,38 @@ def _update_content_list_paths(
) -> 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
@@ -245,42 +233,38 @@ async def cleanup_parser_output_dirs(
) -> 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)
- )
+ 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()):
@@ -288,9 +272,8 @@ async def cleanup_parser_output_dirs(
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
+ return cleaned_count
diff --git a/src/services/search/__init__.py b/src/services/search/__init__.py
index a21a73293..cd89e1d4c 100644
--- a/src/services/search/__init__.py
+++ b/src/services/search/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Web Search Service - Pluggable search provider architecture
diff --git a/src/services/search/base.py b/src/services/search/base.py
index c9e95e615..7249c01a9 100644
--- a/src/services/search/base.py
+++ b/src/services/search/base.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Web Search Base Provider - Abstract base class for all search providers
diff --git a/src/services/search/consolidation.py b/src/services/search/consolidation.py
index 13899ad93..6f304b165 100644
--- a/src/services/search/consolidation.py
+++ b/src/services/search/consolidation.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Answer Consolidation - Generate answers from raw search results
diff --git a/src/services/search/providers/__init__.py b/src/services/search/providers/__init__.py
index bd3a0ab16..70e04991b 100644
--- a/src/services/search/providers/__init__.py
+++ b/src/services/search/providers/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Web Search Provider Registry
diff --git a/src/services/search/providers/baidu.py b/src/services/search/providers/baidu.py
index 88b2493fa..a6a6c752d 100644
--- a/src/services/search/providers/baidu.py
+++ b/src/services/search/providers/baidu.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Baidu AI Search Provider
diff --git a/src/services/search/providers/exa.py b/src/services/search/providers/exa.py
index bc62f7ba8..44b3e0521 100644
--- a/src/services/search/providers/exa.py
+++ b/src/services/search/providers/exa.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Exa Neural Search Provider
diff --git a/src/services/search/providers/jina.py b/src/services/search/providers/jina.py
index b877fdceb..e38c47372 100644
--- a/src/services/search/providers/jina.py
+++ b/src/services/search/providers/jina.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Jina Reader Search Provider
diff --git a/src/services/search/providers/perplexity.py b/src/services/search/providers/perplexity.py
index 54e989333..7f0123f82 100644
--- a/src/services/search/providers/perplexity.py
+++ b/src/services/search/providers/perplexity.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Perplexity AI Search Provider
diff --git a/src/services/search/providers/serper.py b/src/services/search/providers/serper.py
index 9b698269b..2f7e0865e 100644
--- a/src/services/search/providers/serper.py
+++ b/src/services/search/providers/serper.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Serper Google SERP Provider
diff --git a/src/services/search/providers/tavily.py b/src/services/search/providers/tavily.py
index 4668d7d87..e86462f3f 100644
--- a/src/services/search/providers/tavily.py
+++ b/src/services/search/providers/tavily.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Tavily Search Provider
diff --git a/src/services/search/types.py b/src/services/search/types.py
index 8efa75db5..fa1280355 100644
--- a/src/services/search/types.py
+++ b/src/services/search/types.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Web Search Types - Shared dataclasses and type definitions
diff --git a/src/services/setup/__init__.py b/src/services/setup/__init__.py
index e2802873b..28ee5356e 100644
--- a/src/services/setup/__init__.py
+++ b/src/services/setup/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Setup Service
=============
diff --git a/src/services/tts/__init__.py b/src/services/tts/__init__.py
index 7f46c6a14..955261a5f 100644
--- a/src/services/tts/__init__.py
+++ b/src/services/tts/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
TTS Service
===========
diff --git a/src/services/tts/config.py b/src/services/tts/config.py
index ba49ef80b..8e0db7f51 100644
--- a/src/services/tts/config.py
+++ b/src/services/tts/config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
TTS Configuration
=================
diff --git a/tests/services/rag/testfile.html b/tests/services/rag/testfile.html
index 960f0af19..06f0c2239 100644
--- a/tests/services/rag/testfile.html
+++ b/tests/services/rag/testfile.html
@@ -92,4 +92,3 @@
</footer>
</body>
</html>
-
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 65dc9617d..abef3eef4 100644
--- a/web/app/knowledge/page.tsx
+++ b/web/app/knowledge/page.tsx
@@ -193,7 +193,10 @@ export default function KnowledgePage() {
// Get supported extensions for current provider
const getSupportedExtensions = (provider: string): string[] => {
- return PROVIDER_SUPPORTED_EXTENSIONS[provider] || PROVIDER_SUPPORTED_EXTENSIONS.llamaindex;
+ return (
+ PROVIDER_SUPPORTED_EXTENSIONS[provider] ||
+ PROVIDER_SUPPORTED_EXTENSIONS.llamaindex
+ );
};
// Get file type hint for current provider
@@ -314,7 +317,9 @@ export default function KnowledgePage() {
);
});
} else if (entry.isDirectory) {
- return readDirectoryRecursively(entry as unknown as FileSystemDirectoryEntry);
+ return readDirectoryRecursively(
+ entry as unknown as FileSystemDirectoryEntry,
+ );
}
return [];
};