Repository navigation
feat: add native Dutch language support for BM25 tokenization - #14140
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR threads language information through the RAG pipeline to enable language-aware tokenization. Core NLP functions receive a ChangesLanguage-Aware Tokenization Pipeline
Dutch Language Support & Configuration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/nlp/__init__.py (1)
376-399:⚠️ Potential issue | 🟠 Major
engstill sends Dutch table batches through the CJK separator path.This function now receives
language, but row batching still uses"; " if eng else "; ". Current callers deriveengfromlang.lower() == "english", so Dutch and other non-English Latin-script KBs will still get the full-width Chinese separator here. That changes indexed table text even though tokenization is now language-aware.Patch idea
def tokenize_table(tbls, doc, eng, batch_size=10, language="English"): res = [] + lang_key = (language or "English").strip().lower() # add tables for (img, rows), poss in tbls: if not rows: continue if isinstance(rows, str): @@ - de = "; " if eng else "; " + de = "; " if lang_key in {"chinese", "japanese"} else "; " for i in range(0, len(rows), batch_size): d = copy.deepcopy(doc) r = de.join(rows[i:i + batch_size]) tokenize(d, r, eng, language=language)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/nlp/__init__.py` around lines 376 - 399, The table-batching separator should be chosen from the explicit language argument, not the boolean eng flag (which may be false for other Latin languages like Dutch); in tokenize_table replace the de assignment so it uses language (e.g. de = "; " if language.lower().strip() == "english" else "; ") or otherwise check language.lower() for Latin/English instead of using eng, keeping the rest of the batching logic intact; update the line that sets de and any related comments to reference language and ensure language is normalized with .lower().strip() before comparison.
🧹 Nitpick comments (1)
web/src/components/cross-language-form-field.tsx (1)
14-26: Consider eliminating duplication with common.ts.The change correctly adds Dutch to the local
Languagesarray. However, this array duplicates language definitions that also exist incommon.ts(LanguageList). While the arrays serve different purposes (cross-language search options vs. all supported languages), this duplication creates a maintenance burden—updates to one may be forgotten in the other.Suggested consolidation approach
If the cross-language search is meant to support a specific subset of languages, consider either:
- Import and filter from
LanguageList:+import { LanguageList } from '@/constants/common'; + -const Languages = [ - 'English', - 'Chinese', - // ... -]; +const Languages = LanguageList.filter(lang => + ['English', 'Chinese', 'Spanish', 'French', 'German', + 'Japanese', 'Korean', 'Vietnamese', 'Arabic', 'Turkish', 'Dutch'].includes(lang) +);
- Or export a dedicated
CrossLanguageListfromcommon.tsand import it here.This would ensure single source of truth for language additions.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@web/src/components/cross-language-form-field.tsx` around lines 14 - 26, The local Languages array duplicates the master list in common.ts (LanguageList); replace the hardcoded array by importing and using a single source of truth: either import LanguageList from common.ts and filter it to the subset needed for cross-language search, or add and export a dedicated CrossLanguageList from common.ts and import that here; update references to the local Languages symbol to use the imported list and remove the duplicated array declaration.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/app/tag.py`:
- Line 50: The call rag_tokenizer.tokenizer.set_language(lang) mutates a global
tokenizer and causes race conditions in concurrent async tasks (do_handle_task);
instead, stop mutating shared state and create/use a request-local tokenizer
instance per call: add or use a factory on RagTokenizer (e.g.,
RagTokenizer.create_for(lang) or clone_for(lang)) that returns a new tokenizer
configured for the given lang, update do_handle_task and all call sites to use
that per-call instance, and remove calls to
rag_tokenizer.tokenizer.set_language(lang) so RagTokenizer.set_language() is no
longer used to mutate global state.
In `@rag/nlp/__init__.py`:
- Around line 268-274: The function tokenize mutates a shared module-level
tokenizer via rag_tokenizer.tokenizer.set_language(language), which can race
across concurrent ingests; instead, obtain a per-call tokenizer instance and use
it locally: remove the set_language call, call a tokenizer factory (e.g.,
rag_tokenizer.get_tokenizer(language) or clone
rag_tokenizer.tokenizer.clone_with_language(language)) to get a local tokenizer,
then call that instance's tokenize and fine_grained_tokenize methods to populate
d["content_ltks"] and d["content_sm_ltks"]; also ensure the same per-document
language/tokenizer is passed through or recorded for later re-tokenization in
attach_media_context so it doesn't rely on module state.
In `@rag/nlp/rag_tokenizer.py`:
- Around line 94-151: Update the NLTK setup to explicitly download 'punkt' (in
the module that performs NLTK downloads) and log the success/failure, and add
robust error handling around the tokenize method: in the tokenize(self, line:
str) implementation wrap the call to word_tokenize(L) in a try/except that
catches LookupError (or generic Exception), logs an informative message, and
falls back to a safe tokenizer (e.g., simple whitespace split or returning L) so
tokenization doesn't silently fail; ensure the NLTK download call uses
nltk.download('punkt', halt_on_error=False) with the result logged so failures
are visible and validate punkt availability at tokenizer initialization before
first use.
In `@rag/svr/task_executor.py`:
- Around line 343-344: The code currently mutates the module-level singleton via
rag_tokenizer.tokenizer.set_language(...) which causes race conditions under
concurrent async tasks; change to a non-mutating per-call approach: either
create a per-task/local tokenizer instance (e.g., instantiate
rag_tokenizer.Tokenizer(language) inside the executor before tokenization), or
modify/overload tokenize() to accept a language argument so tokenization is
configured per-call instead of calling set_language on the shared singleton; if
you must keep the singleton, wrap set_language + tokenize calls in an atomic
lock (asyncio.Lock) scoped to the tokenizer to prevent interleaving. Also add an
informational log whenever language configuration is applied (use the existing
logger and include task id and language) so calls like
rag_tokenizer.tokenizer.set_language or the new per-call configuration are
recorded. Ensure all locations noted (calls at
rag_tokenizer.tokenizer.set_language) are updated to use the new per-call or
locked pattern and remove mutations of shared state.
---
Outside diff comments:
In `@rag/nlp/__init__.py`:
- Around line 376-399: The table-batching separator should be chosen from the
explicit language argument, not the boolean eng flag (which may be false for
other Latin languages like Dutch); in tokenize_table replace the de assignment
so it uses language (e.g. de = "; " if language.lower().strip() == "english"
else "; ") or otherwise check language.lower() for Latin/English instead of
using eng, keeping the rest of the batching logic intact; update the line that
sets de and any related comments to reference language and ensure language is
normalized with .lower().strip() before comparison.
---
Nitpick comments:
In `@web/src/components/cross-language-form-field.tsx`:
- Around line 14-26: The local Languages array duplicates the master list in
common.ts (LanguageList); replace the hardcoded array by importing and using a
single source of truth: either import LanguageList from common.ts and filter it
to the subset needed for cross-language search, or add and export a dedicated
CrossLanguageList from common.ts and import that here; update references to the
local Languages symbol to use the imported list and remove the duplicated array
declaration.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fcc77da0-3d1c-46f8-8a97-1852e853d385
📒 Files selected for processing (20)
rag/app/audio.pyrag/app/book.pyrag/app/email.pyrag/app/laws.pyrag/app/manual.pyrag/app/naive.pyrag/app/one.pyrag/app/paper.pyrag/app/picture.pyrag/app/presentation.pyrag/app/qa.pyrag/app/resume.pyrag/app/table.pyrag/app/tag.pyrag/nlp/__init__.pyrag/nlp/rag_tokenizer.pyrag/svr/task_executor.pyweb/src/components/cross-language-form-field.tsxweb/src/constants/common.tsweb/src/locales/en.ts
| Every pair will be treated as a chunk. | ||
| """ | ||
| eng = lang.lower() == "english" | ||
| rag_tokenizer.tokenizer.set_language(lang) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "1) Locate tokenizer implementation and language mutation points"
fd -i "rag_tokenizer.py" | while read -r f; do
echo "== $f =="
rg -n "class\s+RagTokenizer|tokenizer\s*=|def\s+set_language|self\.(language|stemmer|lemmatizer)" "$f"
done
echo
echo "2) Find all direct global language mutation call sites"
rg -n --type=py "rag_tokenizer\.tokenizer\.set_language\("
echo
echo "3) Find concurrent execution paths that may interleave these calls"
rg -n --type=py "ThreadPoolExecutor|concurrent\.futures|threading\."Repository: infiniflow/ragflow
Length of output: 22384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Context of rag/app/tag.py line 50 ==="
head -60 rag/app/tag.py | tail -30
echo
echo "=== 2) Full function containing line 50 ==="
rg -B 20 -A 10 "rag_tokenizer\.tokenizer\.set_language" rag/app/tag.py
echo
echo "=== 3) Check if set_language is called within executor blocks (task_executor.py) ==="
rg -B 5 -A 5 "set_language" rag/svr/task_executor.py | head -80
echo
echo "=== 4) Search for synchronization mechanisms on tokenizer ==="
rg -n "threading\.(Lock|RLock|Semaphore)|Lock\(" rag/nlp/rag_tokenizer.py
echo
echo "=== 5) Check RagTokenizer class implementation for thread-safety ==="
sed -n '49,100p' rag/nlp/rag_tokenizer.pyRepository: infiniflow/ragflow
Length of output: 4729
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Find all callers of chunk() function in rag/app/tag.py ==="
rg -n "\.chunk\(" --type=py | head -20
echo
echo "=== 2) Get context of task_executor.py ThreadPoolExecutor usage ==="
sed -n '1030,1045p' rag/svr/task_executor.py
echo
echo "=== 3) Check if task processing happens within executor ==="
rg -B 10 "executor.*submit\|executor.*map\|with.*executor" rag/svr/task_executor.py | head -60
echo
echo "=== 4) Check imports and initialization in tag.py ==="
head -20 rag/app/tag.py
echo
echo "=== 5) Look for thread-local or request-scoped tokenizer patterns ==="
rg -n "threading\.local\|contextvars\|request\..*tokenizer" rag/nlp/rag_tokenizer.pyRepository: infiniflow/ragflow
Length of output: 988
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Context after executor creation in task_executor.py ==="
sed -n '1037,1100p' rag/svr/task_executor.py
echo
echo "=== 2) How chunk() is called in file_service.py ==="
sed -n '550,570p' api/db/services/file_service.py
echo
echo "=== 3) Check if set_progress is async or runs in executor ==="
rg -B 5 -A 10 "def set_progress" rag/svr/task_executor.py | head -40
echo
echo "=== 4) Search for actual executor.submit calls or task running ==="
sed -n '1037,1150p' rag/svr/task_executor.py | grep -A 50 "executor"
echo
echo "=== 5) Check if chunk() parsing happens in concurrent context ==="
rg -B 20 "\.chunk\(" api/db/services/file_service.py | tail -50Repository: infiniflow/ragflow
Length of output: 8120
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Search for executor.submit or executor use in task_executor.py ==="
rg -n "executor\.(submit|map|apply)" rag/svr/task_executor.py
echo
echo "=== 2) Check if parse() endpoint can be called concurrently ==="
rg -B 5 "def parse" api/db/services/file_service.py | head -20
echo
echo "=== 3) Look for FastAPI/Flask route handlers that call chunk/parse ==="
rg -n "@.*route\|@.*post\|@.*get" api/ | grep -i "parse\|chunk" | head -15
echo
echo "=== 4) Check actual concurrent file parsing in file_service ==="
sed -n '530,570p' api/db/services/file_service.py
echo
echo "=== 5) Examine RagTokenizer initialization - is it truly a shared singleton? ==="
sed -n '190,210p' rag/nlp/rag_tokenizer.pyRepository: infiniflow/ragflow
Length of output: 753
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Find API endpoints that call parse() or parse_docs() ==="
rg -n "FileService\.parse\|file_service\.parse" api/ --type=py
echo
echo "=== 2) Look for endpoint definitions that might call chunk indirectly ==="
rg -B 10 "parse_docs\|\.parse\(" api/db/services/ --type=py | grep -E "@.*route|def |parse" | head -30
echo
echo "=== 3) Check if there are API endpoints at all in api/db/services ==="
ls -la api/db/services/*.py | head -10
echo
echo "=== 4) Search in api/apps or similar for endpoint definitions ==="
find api -name "*.py" -type f -exec grep -l "@.*route\|@app\|@router" {} \; | head -10
echo
echo "=== 5) Look for where parse_docs is called ==="
rg -n "parse_docs" --type=py
echo
echo "=== 6) Check if chunk() can be called from async/concurrent context ==="
rg -B 5 "\.chunk\(" rag/app/ --type=py | head -50Repository: infiniflow/ragflow
Length of output: 125
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Check API framework setup ==="
head -50 api/ragflow_server.py
echo
echo "=== 2) Find all uses of parse/chunk in the codebase ==="
rg -n "\.parse\(|\.chunk\(" --type=py | grep -v test | head -20
echo
echo "=== 3) Look at file_service imports and context ==="
head -30 api/db/services/file_service.py
echo
echo "=== 4) Search for async task processing or celery ==="
rg -n "celery\|async def\|await " rag/svr/task_executor.py | head -15
echo
echo "=== 5) Check actual function signature that uses executor.submit ==="
sed -n '1190,1210p' rag/svr/task_executor.py
echo
echo "=== 6) Find where set_language is called in task processing ==="
rg -B 3 -A 3 "set_language" rag/svr/task_executor.py | head -40Repository: infiniflow/ragflow
Length of output: 4093
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Check if chunk() is directly exposed via API endpoint ==="
rg -n "def.*chunk\|@.*route.*chunk" api/ --type=py
echo
echo "=== 2) Find canvas.py and code_exec.py usage context ==="
sed -n '760,775p' agent/canvas.py
echo
echo "=== 3) Check code_exec.py context ==="
sed -n '595,610p' agent/tools/code_exec.py
echo
echo "=== 4) Verify RagTokenizer.set_language modifies shared instance ==="
sed -n '49,75p' rag/nlp/rag_tokenizer.py
echo
echo "=== 5) Check if any logging exists for language switching ==="
rg -n "logging\." rag/app/tag.py | head -10
echo
echo "=== 6) Check if tag.py uses set_language and if any logging is added ==="
sed -n '40,65p' rag/app/tag.pyRepository: infiniflow/ragflow
Length of output: 126
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Full RagTokenizer class definition ==="
sed -n '49,100p' rag/nlp/rag_tokenizer.py
echo
echo "=== 2) Check if logging is already in tag.py chunk() function ==="
sed -n '30,70p' rag/app/tag.py
echo
echo "=== 3) Verify if the changed line is new or modified ==="
git log -p --follow -S "rag_tokenizer.tokenizer.set_language" -- rag/app/tag.py 2>/dev/null | head -80 || echo "Git history not available"
echo
echo "=== 4) Check ruff configuration for the project ==="
cat pyproject.toml 2>/dev/null | grep -A 20 "\[tool.ruff\]" || cat .ruff.toml 2>/dev/null || echo "No ruff config found"
echo
echo "=== 5) Check if tag.py has any logging imports ==="
rg -n "^import logging|^from.*logging" rag/app/tag.pyRepository: infiniflow/ragflow
Length of output: 4631
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Check actual execution flow in task processing ==="
sed -n '980,1050p' rag/svr/task_executor.py | head -60
echo
echo "=== 2) Look for where document parsing happens (after set_language) ==="
sed -n '1200,1250p' rag/svr/task_executor.py | head -40
echo
echo "=== 3) Check if there's per-request or per-task language isolation ==="
rg -B 2 -A 8 "def.*parse.*document\|async def.*run" rag/svr/task_executor.py | head -60
echo
echo "=== 4) Confirm: does each task/request set language once before processing? ==="
rg -B 5 -A 15 "set_language.*task\[" rag/svr/task_executor.py | head -50
echo
echo "=== 5) Check tag.py: does it need logging beyond what set_language() provides? ==="
cat > /tmp/check_logging.py << 'EOF'
import re
# Read tag.py
with open('rag/app/tag.py', 'r') as f:
content = f.read()
# Check for logging import
if 'import logging' in content or 'from logging import' in content:
print("✓ tag.py has logging import")
else:
print("✗ tag.py has NO logging import")
# Check for logger usage
if re.search(r'logger\.|logging\.', content):
print("✓ tag.py uses logging")
else:
print("✗ tag.py does NOT use logging")
# Find the chunk function
chunk_match = re.search(r'def chunk\(.*?\):(.*?)(?=\ndef |\Z)', content, re.DOTALL)
if chunk_match:
chunk_body = chunk_match.group(1)
if 'logging' in chunk_body or 'logger' in chunk_body:
print("✓ chunk() function has logging")
else:
print("✗ chunk() function has NO logging")
print(f" First 500 chars: {chunk_body[:500]}")
EOF
python /tmp/check_logging.pyRepository: infiniflow/ragflow
Length of output: 4302
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Check what calls chunk() from tag.py and in what context ==="
rg -B 10 "tag\.chunk\|from rag\.app import.*tag\|from rag\.app\.tag import" --type=py | head -80
echo
echo "=== 2) Verify the logging in RagTokenizer.set_language is sufficient ==="
sed -n '56,80p' rag/nlp/rag_tokenizer.py
echo
echo "=== 3) Check if tag.py chunk() needs explicit logging besides set_language's logging ==="
sed -n '35,80p' rag/app/tag.py
echo
echo "=== 4) Analyze: is the race condition real given task execution pattern? ==="
echo "Looking at do_handle_task flow:"
echo " 1. set_language(task_language) at line 1013"
echo " 2. executor = ThreadPoolExecutor() at line 1037"
echo " 3. executor.submit() at line 1199"
echo "So set_language is called BEFORE executor tasks run - per task, not concurrent"
echo
echo "=== 5) Check if chunk() in tag.py is called from concurrent context ==="
rg -n "\.chunk\|tag\.chunk" api/db/services/file_service.py
echo
echo "=== 6) Determine: does tag.py.chunk() need logging per guidelines? ==="
cat > /tmp/check_tag_logging.py << 'EOF'
import ast
import sys
with open('rag/app/tag.py', 'r') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == 'chunk':
print(f"chunk() function found at line {node.lineno}")
# Check body for logging
has_logging = any('logging' in ast.dump(child).lower() for child in ast.walk(node))
print(f" Has logging calls: {has_logging}")
# Show first few statements
for i, stmt in enumerate(node.body[:10]):
if isinstance(stmt, ast.Expr):
print(f" Line {stmt.lineno}: {ast.dump(stmt.value)[:60]}...")
else:
print(f" Line {stmt.lineno}: {type(stmt).__name__}")
EOF
python /tmp/check_tag_logging.pyRepository: infiniflow/ragflow
Length of output: 129
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== 1) Simple check: where is chunk() from tag.py actually used? ==="
rg "from rag\.app.*import.*tag|from rag\.app import tag|tag\.chunk" --type=py -n 2>/dev/null || echo "No matches found"
echo
echo "=== 2) Search for all chunk() function definitions ==="
rg "def chunk\(" --type=py -n
echo
echo "=== 3) Confirm: RagTokenizer has logging for set_language ==="
grep -n "logger\." rag/nlp/rag_tokenizer.py
echo
echo "=== 4) Check what imports tag.py has ==="
head -15 rag/app/tag.py
echo
echo "=== 5) Synthesize findings: is set_language in tag.py called concurrently? ==="
echo "Execution flow:"
echo " - file_service.parse() calls chunk() from tag module"
echo " - chunk() is NOT in executor, runs synchronously"
echo " - set_language() ALREADY has logging in RagTokenizer"
echo " - Therefore: no new logging needed in tag.py per guidelines"
echo " - However: race condition IS real IF multiple tasks run async concurrently"Repository: infiniflow/ragflow
Length of output: 3022
Race condition confirmed: shared tokenizer language can be overwritten by concurrent tasks.
Line 50 calls rag_tokenizer.tokenizer.set_language(lang), which mutates a global singleton instance. Since do_handle_task() is async and multiple tasks can run concurrently, Task A and Task B can interleave set_language() calls, causing one to overwrite the other's language setting mid-processing. This produces incorrect tokens for one of the tasks.
Logging for this operation already exists in RagTokenizer.set_language() (rag/nlp/rag_tokenizer.py:74, 80).
The fix requires architectural change: move to request-local or per-call tokenizer instances instead of mutating shared state. The language argument is already available at all call sites.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/app/tag.py` at line 50, The call
rag_tokenizer.tokenizer.set_language(lang) mutates a global tokenizer and causes
race conditions in concurrent async tasks (do_handle_task); instead, stop
mutating shared state and create/use a request-local tokenizer instance per
call: add or use a factory on RagTokenizer (e.g., RagTokenizer.create_for(lang)
or clone_for(lang)) that returns a new tokenizer configured for the given lang,
update do_handle_task and all call sites to use that per-call instance, and
remove calls to rag_tokenizer.tokenizer.set_language(lang) so
RagTokenizer.set_language() is no longer used to mutate global state.
| def tokenize(d, txt, eng, language="English"): | ||
| from . import rag_tokenizer | ||
| rag_tokenizer.tokenizer.set_language(language) | ||
| d["content_with_weight"] = txt | ||
| t = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", txt) | ||
| d["content_ltks"] = rag_tokenizer.tokenize(t) | ||
| d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"]) |
There was a problem hiding this comment.
Avoid mutating the shared tokenizer inside tokenize().
At Lines 270-273, rag_tokenizer.tokenizer.set_language(language) updates a module-level singleton immediately before tokenization. Concurrent ingests with different KB languages can interleave here and emit stems with the wrong stemmer/lemmatizer; the later re-tokenization path in attach_media_context() also becomes dependent on whichever language was set most recently. Please make language selection part of a per-call or thread-local tokenizer instead of shared mutable state.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/nlp/__init__.py` around lines 268 - 274, The function tokenize mutates a
shared module-level tokenizer via
rag_tokenizer.tokenizer.set_language(language), which can race across concurrent
ingests; instead, obtain a per-call tokenizer instance and use it locally:
remove the set_language call, call a tokenizer factory (e.g.,
rag_tokenizer.get_tokenizer(language) or clone
rag_tokenizer.tokenizer.clone_with_language(language)) to get a local tokenizer,
then call that instance's tokenize and fine_grained_tokenize methods to populate
d["content_ltks"] and d["content_sm_ltks"]; also ensure the same per-document
language/tokenizer is passed through or recorded for later re-tokenization in
attach_media_context so it doesn't rely on module state.
| rag_tokenizer.tokenizer.set_language(task["language"]) | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if tokenizer is a module-level singleton used across concurrent paths
rg -n "rag_tokenizer\.tokenizer" --type=py -C2 | head -60Repository: infiniflow/ragflow
Length of output: 2703
🏁 Script executed:
# First, find the rag_tokenizer module to understand if it's a singleton
fd -t f "rag_tokenizer" --type pyRepository: infiniflow/ragflow
Length of output: 231
🏁 Script executed:
# Check the tokenizer class definition and set_language method
rg -n "class.*Tokenizer|def set_language" --type=py -A5 | head -100Repository: infiniflow/ragflow
Length of output: 2656
🏁 Script executed:
# Check if the functions in task_executor.py are async
rg -n "^async def|^def" rag/svr/task_executor.py | grep -E "(upload_to_minio|run_dataflow|run_raptor_for_kb|do_handle_task)"Repository: infiniflow/ragflow
Length of output: 254
🏁 Script executed:
# Check MAX_CONCURRENT_TASKS value
rg -n "MAX_CONCURRENT_TASKS" --type=py -B2 -A2Repository: infiniflow/ragflow
Length of output: 1498
🏁 Script executed:
# Check if logging is added for the language setting changes
rg -n "set_language" rag/svr/task_executor.py -B3 -A3Repository: infiniflow/ragflow
Length of output: 1519
🏁 Script executed:
# Check how rag_tokenizer is initialized (singleton pattern)
rg -n "tokenizer\s*=" rag/nlp/__init__.py -B3 -A3Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Get the full set_language implementation
sed -n '56,85p' rag/nlp/rag_tokenizer.pyRepository: infiniflow/ragflow
Length of output: 1495
🏁 Script executed:
# Check upload_to_minio function signature
rg -n "def upload_to_minio" rag/svr/task_executor.py -A5Repository: infiniflow/ragflow
Length of output: 362
🏁 Script executed:
# Check if there's a function that wraps the set_language calls with logging
rg -n "logging.info|logging.debug" rag/svr/task_executor.py | grep -i "language\|tokeniz"Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Check how rag_tokenizer is actually used - check the import and initialization
cat -n rag/nlp/__init__.py | head -50Repository: infiniflow/ragflow
Length of output: 2654
🏁 Script executed:
# Look for the actual tokenizer instantiation
rg -n "tokenizer\s*=" rag/nlp/__init__.pyRepository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Check if upload_to_minio is called concurrently
rg -n "upload_to_minio" rag/svr/task_executor.py -B2 -A2Repository: infiniflow/ragflow
Length of output: 396
🏁 Script executed:
# Verify the ruff formatting/linting status of task_executor.py
head -30 rag/svr/task_executor.pyRepository: infiniflow/ragflow
Length of output: 1051
🏁 Script executed:
# Check the context around each set_language call to see if there's logging nearby
sed -n '340,348p' rag/svr/task_executor.py
sed -n '649,654p' rag/svr/task_executor.py
sed -n '809,818p' rag/svr/task_executor.py
sed -n '1024,1032p' rag/svr/task_executor.pyRepository: infiniflow/ragflow
Length of output: 1651
🏁 Script executed:
# Find where rag_tokenizer is actually instantiated as a module-level singleton
grep -n "rag_tokenizer\s*=" rag/nlp/__init__.py | tail -20Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Look at the end of rag/nlp/__init__.py to find the tokenizer instantiation
tail -50 rag/nlp/__init__.pyRepository: infiniflow/ragflow
Length of output: 1862
🏁 Script executed:
# Search for RagTokenizer instantiation across the codebase
rg -n "RagTokenizer()" --type pyRepository: infiniflow/ragflow
Length of output: 307
🏁 Script executed:
# Check if the tokenizer is truly shared across all these calls
rg -n "from.*rag_tokenizer|import.*rag_tokenizer" --type py | head -20Repository: infiniflow/ragflow
Length of output: 1512
🏁 Script executed:
# Check if there's any logging added in the new code around set_language calls
rg -n "logging\." rag/svr/task_executor.py | grep -E "(343|651|812|1027)"Repository: infiniflow/ragflow
Length of output: 44
🏁 Script executed:
# Verify the actual line numbers and context for logging around set_language
sed -n '341,345p; 649,653p; 810,814p; 1025,1029p' rag/svr/task_executor.pyRepository: infiniflow/ragflow
Length of output: 1076
🏁 Script executed:
# Check if ruff is configured for this project
fd -e "pyproject.toml|ruff.toml|setup.cfg" | xargs grep -l "ruff" 2>/dev/null || echo "No ruff config found"Repository: infiniflow/ragflow
Length of output: 82
🏁 Script executed:
# Get the context to understand if these are "new flows"
# Check git blame or annotations for these lines (if available)
git log --oneline -n 20 -- rag/svr/task_executor.pyRepository: infiniflow/ragflow
Length of output: 117
Race condition: shared tokenizer singleton mutated across concurrent async tasks.
The rag_tokenizer.tokenizer is a module-level singleton instantiated once and imported across the codebase. The set_language() method mutates instance state (self.stemmer, self._use_lemmatizer). With MAX_CONCURRENT_TASKS=5, multiple async tasks can interleave, causing one task's language setting to affect another task's tokenization.
Example scenario:
- Task A (Dutch) calls
set_language("Dutch")at line 1027 - Task A awaits I/O
- Task B (English) calls
set_language("English")at line 651 - Task A resumes and tokenizes with English stemmer instead of Dutch
Additionally, no logging is added for these language configuration changes, which violates the coding guideline requiring logging for new flows.
Consider one of these approaches:
- Use a thread-local or context-local tokenizer instance
- Pass language to
tokenize()directly and configure per-call - Protect language setting + tokenization as an atomic operation
- Add logging for language configuration changes
Applies to: lines 343, 651, 812, 1027
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/svr/task_executor.py` around lines 343 - 344, The code currently mutates
the module-level singleton via rag_tokenizer.tokenizer.set_language(...) which
causes race conditions under concurrent async tasks; change to a non-mutating
per-call approach: either create a per-task/local tokenizer instance (e.g.,
instantiate rag_tokenizer.Tokenizer(language) inside the executor before
tokenization), or modify/overload tokenize() to accept a language argument so
tokenization is configured per-call instead of calling set_language on the
shared singleton; if you must keep the singleton, wrap set_language + tokenize
calls in an atomic lock (asyncio.Lock) scoped to the tokenizer to prevent
interleaving. Also add an informational log whenever language configuration is
applied (use the existing logger and include task id and language) so calls like
rag_tokenizer.tokenizer.set_language or the new per-call configuration are
recorded. Ensure all locations noted (calls at
rag_tokenizer.tokenizer.set_language) are updated to use the new per-call or
locked pattern and remove mutations of shared state.
qinling0210
left a comment
There was a problem hiding this comment.
There is also tokenization logic in C++ in Infinity (RAGAnalyzer::Tokenize, RAGAnalyzer::TokenizeWithPosition), we need to support Dutch too and make the tokenization results are the same between C++ and Python (unit test rag_analyzer_ut.cpp).
There was a problem hiding this comment.
Full rag_tokenizer.py is in Infinity (https://github.com/infiniflow/infinity/blob/main/python/infinity_sdk/infinity/rag_tokenizer.py), we import the file from infinity-sdk in ragflow.
We should not modify this file. I suggest you submit a PR to modify rag_tokenizer.py in Infinity.
After we release a new version of Infinity, we can merge this PR in ragflow
|
Thanks for the review, @qinling0210! You're right that the C++ Infinity tokenizer (RAGAnalyzer) would need Dutch support too for full parity. To be transparent about scope: this PR focuses on the Python-side tokenization path (BM25 via NLTK/Snowball), which is what most deployments use today. I don't have experience with the Infinity C++ codebase and wouldn't be able to confidently make changes there without risking regressions. Would it be acceptable to merge this as Python-only Dutch support for now, and track the C++ Infinity side as a follow-up issue? I'm happy to create that issue with details on the expected tokenization behavior so someone familiar with the C++ side can pick it up. Alternatively, if C++ parity is a hard requirement before merge, I understand — just let me know. I've also pushed a fix for the table separator bug flagged in the automated review — Latin-script languages like Dutch were incorrectly getting the CJK full-width separator ( |
|
Regarding the thread-safety concerns raised by the automated review ( The task executor spawns separate OS processes via |
dc11f73 to
ad7500f
Compare
|
OK, we will handle tokenization logic in C++ in Infinity. You do not need to modify C++ codebase in Infinity. For rag/nlp/rag_toknizer.py in Ragflow, we can import the code from Infinity. |
ad7500f to
3958ab0
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
rag/nlp/__init__.py (1)
696-702:⚠️ Potential issue | 🟡 Minor
attach_media_context()re-tokenization inherits whichever language is currently set.
rag_tokenizer.tokenize(combined)andrag_tokenizer.fine_grained_tokenize(...)here do not callset_language(), so re-tokenized content for table/image context will use whatever language was last applied viatokenize()(possibly from a prior document/KB in the same process). If this function can be invoked outside the immediate scope of the most recenttokenize(..., language=...)call (or for documents whose KB language differs from that earlier call), tokens here will be inconsistent with the original chunk's language.Consider threading a
languageargument intoattach_media_context()and callingrag_tokenizer.tokenizer.set_language(language)here too, mirroring the pattern intokenize().🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/nlp/__init__.py` around lines 696 - 702, attach_media_context currently re-tokenizes media context using rag_tokenizer.tokenize(...) and rag_tokenizer.fine_grained_tokenize(...) without setting language, so tokens can inherit whatever language was last used; update attach_media_context to accept a language parameter (e.g., language) and before calling rag_tokenizer.tokenize or .fine_grained_tokenize call rag_tokenizer.tokenizer.set_language(language) (or rag_tokenizer.set_language if available) to mirror the pattern used in tokenize(), and ensure any callers pass through the appropriate KB/document language when invoking attach_media_context so re-tokenization is consistent with the original chunk language.rag/app/table.py (1)
470-499:⚠️ Potential issue | 🟡 MinorPer-row cell tokenization runs with stale language state.
Inside the
for ii, row in df.iterrows()loop, each text-type cell is stemmed viarag_tokenizer.tokenize(row[clmns[j]])at Line 488 beforetokenize(d, formatted_text, eng, language=lang)at Line 498 callsset_language(lang). So the per-cell*_tksfields use the singleton's previously-configured language (English on first-ever invocation, or the last KB's language otherwise) while the row-levelcontent_ltksuses the correct language. The two halves of the same row's index can end up stemmed inconsistently.Suggest configuring language once before the loop:
♻️ Proposed fix
+ rag_tokenizer.tokenizer.set_language(lang) eng = lang.lower() == "english" # is_english(txts) for ii, row in df.iterrows():The same applies to the title tokenization at Lines 472 and 501.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/app/table.py` around lines 470 - 499, Per-row tokenization uses rag_tokenizer.tokenize(...) before the row-level tokenize(d, formatted_text, eng, language=lang) sets the tokenizer language, producing inconsistent stems; fix by configuring the tokenizer language at the start of processing each file/row (call rag_tokenizer.set_language(lang) or the tokenizer's equivalent) before any rag_tokenizer.tokenize(...) calls (i.e., before creating title_tks and before tokenizing any cell values in the loop over df with rag_tokenizer.tokenize and before calling tokenize(d, ...)), so both per-cell fields and the row-level content use the same language.
♻️ Duplicate comments (1)
rag/nlp/rag_tokenizer.py (1)
56-80:⚠️ Potential issue | 🟡 Minor
set_languagesilently keeps prior tokenizer for unsupported languages.When
languageis not in_SNOWBALL_LANGUAGE_MAP(Lines 76–80), the method only logs at DEBUG and leaves whatever stemmer/lemmatizer was last configured on the singleton. Combined with the module-level singleton at Line 197, this means: if Task A sets Dutch and Task B requests Japanese (unmapped), Task B will silently inherit Dutch stemming for any non-CJK tokens that slip through. Consider explicitly resetting to the English defaults on the unsupported branch to make behavior deterministic regardless of call order:🛡️ Proposed reset on unmapped language
else: - # Unsupported language (Chinese, Japanese, Korean, etc.) – keep - # parent defaults (English stemmer/lemmatizer). The tokenize() - # path for CJK text does not apply stemming anyway. - logger.debug("Language '%s' has no Snowball stemmer; keeping defaults", language) + # Unsupported language (Chinese, Japanese, Korean, etc.) – reset + # to English defaults so behavior doesn't depend on prior calls + # on this singleton. The tokenize() path for CJK text does not + # apply stemming anyway. + self.stemmer = SnowballStemmer("english") + self.lemmatizer = WordNetLemmatizer() + self._use_lemmatizer = True + logger.debug("Language '%s' has no Snowball stemmer; reset to English defaults", language)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/nlp/rag_tokenizer.py` around lines 56 - 80, The set_language method currently leaves prior stemmer/lemmatizer when language is not in _SNOWBALL_LANGUAGE_MAP; update the unsupported-language branch in set_language to explicitly reset tokenizer state to the English defaults by assigning a SnowballStemmer for "english", setting lemmatizer = WordNetLemmatizer(), and _use_lemmatizer = True (or otherwise set the same module-level defaults used for the singleton), and keep the debug log; reference set_language, _SNOWBALL_LANGUAGE_MAP, stemmer, lemmatizer, and _use_lemmatizer when making the change.
🧹 Nitpick comments (2)
rag/svr/task_executor.py (1)
665-665:run_dataflowmay run beforedo_handle_tasksets language fordataflowtasks.For the early-exit
dataflow + CANVAS_DEBUG_DOC_IDbranch at Lines 1051–1053,run_dataflow()is invoked beforetask_language = task["language"]at Line 1060. Withinrun_dataflowtheset_languagehere at Line 665 usestask.get("language", "English"), so this branch is OK. But note that the standarddo_handle_taskpath at Line 1099 invokesrun_dataflow(task)after Line 1061 has already set the language; the second call here at Line 665 then overwrites it with the same value. Functionally fine, just redundant — consider dropping thisset_languagecall and relying ondo_handle_taskto do it once, to reduce surface area for the race noted above.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/svr/task_executor.py` at line 665, Remove the redundant rag_tokenizer.tokenizer.set_language call from run_dataflow and instead ensure callers set the language once before invoking run_dataflow: keep do_handle_task assigning task_language (and calling rag_tokenizer.tokenizer.set_language(task["language"])) prior to calling run_dataflow, and update the early-exit dataflow + CANVAS_DEBUG_DOC_ID branch to set rag_tokenizer.tokenizer.set_language(task.get("language", "English")) before it calls run_dataflow(task); this removes the race surface and avoids double-setting language.rag/nlp/rag_tokenizer.py (1)
88-92: Stemmer applied to leading/trailing hyphens and underscores.
re.match(r"[a-zA-Z_-]+$", t)matches tokens that are entirely composed of letters, hyphens, or underscores in any position — including pathological cases like"-","__", or"--foo--". Snowball and WordNet are not designed for such inputs and will return them unchanged, but the regex also permits surrogate-empty tokens like"_"to flow through stemming without effect. More importantly,re.matchalready anchors at the start; the trailing$is fine, but consider requiring at least one alphabetic character to avoid wasted stemmer/lemmatizer calls:♻️ Proposed regex tightening
- if re.match(r"[a-zA-Z_-]+$", t): + if re.match(r"(?=.*[a-zA-Z])[a-zA-Z_-]+$", t):Minor — defer if you want to preserve exact parity with the parent class behavior.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/nlp/rag_tokenizer.py` around lines 88 - 92, Tighten the token check so we only call self.stemmer/self.lemmatizer for tokens that contain at least one alphabetic character (avoiding inputs like "_" or "--"); in the block that checks re.match(r"[a-zA-Z_-]+$", t) (the snippet using variable t and methods self.stemmer and self.lemmatizer), replace the regex with one that requires at least one letter (e.g. use a full-match or anchored pattern like r"^(?=.*[A-Za-z])[A-Za-z_-]+$" or use re.fullmatch with the same character class) so tokens without any alphabetic characters skip stemming/lemmatization.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/app/one.py`:
- Around line 163-166: The title is being tokenized with the tokenizer's prior
language setting because rag_tokenizer.tokenize(...) and
rag_tokenizer.fine_grained_tokenize(...) run before tokenize(doc, ...,
language=lang) sets the language; fix by ensuring the tokenizer language is set
to lang before title tokenization — either call
rag_tokenizer.tokenizer.set_language(lang) (or rag_tokenizer.set_language if
available) at the start of the function or move the two title tokenization calls
to after the tokenize(doc, ..., language=lang) call so title_tks and
title_sm_tks are produced with the correct language; update the same pattern
wherever rag_tokenizer.tokenize and rag_tokenizer.fine_grained_tokenize are used
before language is configured.
In `@rag/nlp/rag_tokenizer.py`:
- Around line 94-151: The current tokenize() duplicates the parent CJK
segmentation logic (max_forward/_max_backward, dfs_, _sort_tokens,
_split_by_lang) which creates maintenance drift; replace the hand-copied
implementation by calling the parent tokenizer and post-processing its tokens:
call super().tokenize(line) (and similarly for fine_grained_tokenize()), split
the returned token string into tokens, apply self._normalize_token() only to
non-Chinese/alphabetic tokens, then rejoin and return the final token string so
future fixes in RagTokenizer.tokenize are preserved; reference the methods
tokenize, fine_grained_tokenize, and _normalize_token to locate the changes.
- Line 49: The local RagTokenizer class duplicates upstream logic
(tokenize/fine_grained_tokenize) and should be removed in favor of importing the
canonical implementation from the Infinity SDK to avoid drift; replace the local
class with a thin import/export that uses infinity.rag_tokenizer.RagTokenizer
(remove/undo overrides of tokenize() and fine_grained_tokenize), and move any
Snowball/set_language integration as a targeted PR against
infinity/python/infinity_sdk/infinity/rag_tokenizer.py so that language handling
(CJK segmentation, DFS scoring, Q2B/traditional conversion) is implemented
upstream rather than duplicated here.
---
Outside diff comments:
In `@rag/app/table.py`:
- Around line 470-499: Per-row tokenization uses rag_tokenizer.tokenize(...)
before the row-level tokenize(d, formatted_text, eng, language=lang) sets the
tokenizer language, producing inconsistent stems; fix by configuring the
tokenizer language at the start of processing each file/row (call
rag_tokenizer.set_language(lang) or the tokenizer's equivalent) before any
rag_tokenizer.tokenize(...) calls (i.e., before creating title_tks and before
tokenizing any cell values in the loop over df with rag_tokenizer.tokenize and
before calling tokenize(d, ...)), so both per-cell fields and the row-level
content use the same language.
In `@rag/nlp/__init__.py`:
- Around line 696-702: attach_media_context currently re-tokenizes media context
using rag_tokenizer.tokenize(...) and rag_tokenizer.fine_grained_tokenize(...)
without setting language, so tokens can inherit whatever language was last used;
update attach_media_context to accept a language parameter (e.g., language) and
before calling rag_tokenizer.tokenize or .fine_grained_tokenize call
rag_tokenizer.tokenizer.set_language(language) (or rag_tokenizer.set_language if
available) to mirror the pattern used in tokenize(), and ensure any callers pass
through the appropriate KB/document language when invoking attach_media_context
so re-tokenization is consistent with the original chunk language.
---
Duplicate comments:
In `@rag/nlp/rag_tokenizer.py`:
- Around line 56-80: The set_language method currently leaves prior
stemmer/lemmatizer when language is not in _SNOWBALL_LANGUAGE_MAP; update the
unsupported-language branch in set_language to explicitly reset tokenizer state
to the English defaults by assigning a SnowballStemmer for "english", setting
lemmatizer = WordNetLemmatizer(), and _use_lemmatizer = True (or otherwise set
the same module-level defaults used for the singleton), and keep the debug log;
reference set_language, _SNOWBALL_LANGUAGE_MAP, stemmer, lemmatizer, and
_use_lemmatizer when making the change.
---
Nitpick comments:
In `@rag/nlp/rag_tokenizer.py`:
- Around line 88-92: Tighten the token check so we only call
self.stemmer/self.lemmatizer for tokens that contain at least one alphabetic
character (avoiding inputs like "_" or "--"); in the block that checks
re.match(r"[a-zA-Z_-]+$", t) (the snippet using variable t and methods
self.stemmer and self.lemmatizer), replace the regex with one that requires at
least one letter (e.g. use a full-match or anchored pattern like
r"^(?=.*[A-Za-z])[A-Za-z_-]+$" or use re.fullmatch with the same character
class) so tokens without any alphabetic characters skip stemming/lemmatization.
In `@rag/svr/task_executor.py`:
- Line 665: Remove the redundant rag_tokenizer.tokenizer.set_language call from
run_dataflow and instead ensure callers set the language once before invoking
run_dataflow: keep do_handle_task assigning task_language (and calling
rag_tokenizer.tokenizer.set_language(task["language"])) prior to calling
run_dataflow, and update the early-exit dataflow + CANVAS_DEBUG_DOC_ID branch to
set rag_tokenizer.tokenizer.set_language(task.get("language", "English")) before
it calls run_dataflow(task); this removes the race surface and avoids
double-setting language.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0d9e0c5a-ded2-4274-8c98-6edec569a572
📒 Files selected for processing (18)
.gitignorerag/app/audio.pyrag/app/book.pyrag/app/email.pyrag/app/laws.pyrag/app/manual.pyrag/app/naive.pyrag/app/one.pyrag/app/paper.pyrag/app/picture.pyrag/app/presentation.pyrag/app/qa.pyrag/app/resume.pyrag/app/table.pyrag/app/tag.pyrag/nlp/__init__.pyrag/nlp/rag_tokenizer.pyrag/svr/task_executor.py
✅ Files skipped from review due to trivial changes (4)
- rag/app/resume.py
- .gitignore
- rag/app/paper.py
- rag/app/naive.py
🚧 Files skipped from review as they are similar to previous changes (7)
- rag/app/audio.py
- rag/app/tag.py
- rag/app/email.py
- rag/app/qa.py
- rag/app/presentation.py
- rag/app/picture.py
- rag/app/manual.py
| doc = {"docnm_kwd": filename, "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))} | ||
| doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"]) | ||
| tokenize(doc, "\n".join(sections), eng) | ||
| tokenize(doc, "\n".join(sections), eng, language=lang) | ||
| return [doc] |
There was a problem hiding this comment.
Title is tokenized before language is configured.
rag_tokenizer.tokenize(...) and fine_grained_tokenize(...) at Lines 163–164 run before tokenize(doc, "\n".join(sections), eng, language=lang) at Line 165 calls set_language(lang). So the document title (title_tks/title_sm_tks) is stemmed with whatever language the singleton was previously configured with — which for the first-ever doc in a process defaults to English, but for subsequent docs could be any prior KB's language.
Either move language configuration earlier (call rag_tokenizer.tokenizer.set_language(lang) once at function entry) or have the title tokenization happen after the body tokenize(...) call. The same pattern likely exists across the other rag/app/*.py files in this PR.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/app/one.py` around lines 163 - 166, The title is being tokenized with the
tokenizer's prior language setting because rag_tokenizer.tokenize(...) and
rag_tokenizer.fine_grained_tokenize(...) run before tokenize(doc, ...,
language=lang) sets the language; fix by ensuring the tokenizer language is set
to lang before title tokenization — either call
rag_tokenizer.tokenizer.set_language(lang) (or rag_tokenizer.set_language if
available) at the start of the function or move the two title tokenization calls
to after the tokenize(doc, ..., language=lang) call so title_tks and
title_sm_tks are produced with the correct language; update the same pattern
wherever rag_tokenizer.tokenize and rag_tokenizer.fine_grained_tokenize are used
before language is configured.
| } | ||
|
|
||
|
|
||
| class RagTokenizer(infinity.rag_tokenizer.RagTokenizer): |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Maintainer requested moving these changes to the Infinity SDK.
Per the maintainer's prior feedback on this file, rag_tokenizer.py should be imported from infinity-sdk rather than diverged in RAGFlow. The whole-method override of tokenize()/fine_grained_tokenize() here duplicates parent logic verbatim, which will silently drift if/when the upstream Infinity tokenizer changes (CJK segmentation, DFS scoring, Q2B/traditional handling). Consider raising the Snowball/set_language() integration as a PR against infinity/python/infinity_sdk/infinity/rag_tokenizer.py and keeping this file as a thin import.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/nlp/rag_tokenizer.py` at line 49, The local RagTokenizer class duplicates
upstream logic (tokenize/fine_grained_tokenize) and should be removed in favor
of importing the canonical implementation from the Infinity SDK to avoid drift;
replace the local class with a thin import/export that uses
infinity.rag_tokenizer.RagTokenizer (remove/undo overrides of tokenize() and
fine_grained_tokenize), and move any Snowball/set_language integration as a
targeted PR against infinity/python/infinity_sdk/infinity/rag_tokenizer.py so
that language handling (CJK segmentation, DFS scoring, Q2B/traditional
conversion) is implemented upstream rather than duplicated here.
| def tokenize(self, line: str) -> str: | ||
| from common import settings # moved from the top of the file to avoid circular import | ||
| from common import settings # moved from the top of the file to avoid circular import | ||
| if settings.DOC_ENGINE_INFINITY: | ||
| return line | ||
| else: | ||
| return super().tokenize(line) | ||
|
|
||
| # --- replicate parent tokenize() but use _normalize_token() --- | ||
| line = re.sub(r"\W+", " ", line) | ||
| line = self._strQ2B(line).lower() | ||
| line = self._tradi2simp(line) | ||
|
|
||
| arr = self._split_by_lang(line) | ||
| res = [] | ||
| for L, lang in arr: | ||
| if not lang: | ||
| # Non-Chinese text: tokenize and normalize | ||
| res.extend([self._normalize_token(t) for t in word_tokenize(L)]) | ||
| continue | ||
| if len(L) < 2 or re.match(r"[a-z\.-]+$", L) or re.match(r"[0-9\.-]+$", L): | ||
| res.append(L) | ||
| continue | ||
|
|
||
| # Chinese dictionary segmentation (max_forward + max_backward + dfs_ merge) | ||
| tks, s = self._max_forward(L) | ||
| tks1, s1 = self._max_backward(L) | ||
|
|
||
| if tks1 == tks: | ||
| res.append(" ".join(tks)) | ||
| else: | ||
| if s1 > s: | ||
| tks = tks1 | ||
| diff = [0 for _ in range(max(len(tks), len(tks1)))] | ||
| for j in range(min(len(tks), len(tks1))): | ||
| if tks[j] != tks1[j]: | ||
| diff[j] = 1 | ||
|
|
||
| i = 0 | ||
| while i < len(tks): | ||
| s = i | ||
| while i < len(diff) and diff[i] == 0: | ||
| i += 1 | ||
| if i > s: | ||
| res.append(" ".join(tks[s:i])) | ||
| if i >= len(diff): | ||
| break | ||
| s = i | ||
| while i < len(diff) and diff[i] == 1: | ||
| i += 1 | ||
|
|
||
| secs = "".join(tks[s:i]) | ||
| tkslist = [] | ||
| self.dfs_(secs, 0, [], tkslist) | ||
| if not tkslist: | ||
| res.append(secs) | ||
| else: | ||
| stk = self._sort_tokens(tkslist)[0][0] | ||
| res.append(" ".join(stk)) | ||
|
|
||
| return " ".join(res) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Reproduced parent logic creates a maintenance liability.
tokenize() and fine_grained_tokenize() (Lines 94–178) now hand-copy the parent class's CJK segmentation, max-forward/backward merging, and DFS scoring instead of delegating to super(). Any future correctness fix or perf improvement in infinity.rag_tokenizer.RagTokenizer.tokenize will be silently lost here.
A less invasive approach is to keep super().tokenize(line) and only post-process its output to apply _normalize_token to the alphabetic segments, e.g. by overriding a smaller hook or by re-stemming tokens after the parent returns. If parent helpers like _split_by_lang, _max_forward, dfs_, _sort_tokens are not stable public API, even better to push this change into Infinity (per maintainer guidance) so the fork is unnecessary.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@rag/nlp/rag_tokenizer.py` around lines 94 - 151, The current tokenize()
duplicates the parent CJK segmentation logic (max_forward/_max_backward, dfs_,
_sort_tokens, _split_by_lang) which creates maintenance drift; replace the
hand-copied implementation by calling the parent tokenizer and post-processing
its tokens: call super().tokenize(line) (and similarly for
fine_grained_tokenize()), split the returned token string into tokens, apply
self._normalize_token() only to non-Chinese/alphabetic tokens, then rejoin and
return the final token string so future fixes in RagTokenizer.tokenize are
preserved; reference the methods tokenize, fine_grained_tokenize, and
_normalize_token to locate the changes.
|
@qinling0210 Thanks for the guidance! I've submitted the tokenizer changes to the Infinity SDK: infiniflow/infinity#3356 — adds The changes are minimal and backward-compatible — default English behavior is unchanged, and callers that never call Once that's merged and released, I'll update this RAGFlow PR to:
Let me know if anything needs adjusting on the Infinity PR side. |
## Summary Add `set_language()` method to `RagTokenizer` to configure the Snowball stemmer per language, enabling proper BM25 tokenization for Dutch, German, French, Spanish, and 12 other Snowball-supported languages. ## Motivation RAGFlow's knowledge bases support a configurable language parameter, but the tokenizer always uses English stemming/lemmatization regardless of the configured language. This means non-English Latin-script languages get incorrect stems during BM25 indexing. For example, the Dutch word "huizen" (houses) should stem to "huis" but currently stems to "huizen" (English stemmer doesn't recognize it). This was requested by the RAGFlow maintainer @qinling0210 in [ragflow#14140](infiniflow/ragflow#14140 (comment)) -- the language-aware tokenizer changes should live in the Infinity SDK so RAGFlow can import them. ## Changes - **`_SNOWBALL_LANGUAGE_MAP`**: Maps 17 language names to NLTK Snowball stemmer names - **`set_language(language)`**: Configures the stemmer for the given language. Disables the WordNet lemmatizer for non-English languages (WordNet only supports English) - **`_normalize_token(t)`**: Extracted from inline stemming logic in `tokenize()` and `english_normalize_()`. Applies stemming (+ optional lemmatization) to alphabetic tokens - **`english_normalize_(tks)`**: Now delegates to `_normalize_token()` -- same behavior, less duplication - **`tokenize()`**: Uses `_normalize_token()` instead of hardcoded `self.stemmer.stem(self.lemmatizer.lemmatize(t))` ## Backward compatibility - Default behavior is **unchanged**: `__init__` sets English stemmer + WordNet lemmatizer, `_use_lemmatizer = True` - Callers that never call `set_language()` get identical results - No new dependencies -- NLTK `SnowballStemmer` already supports all listed languages - `english_normalize_()` produces identical output for English (refactored, not changed) ## Design notes - **Why `set_language()` instead of per-call parameter?** Matches the existing pattern where `stemmer` and `lemmatizer` are instance attributes. RAGFlow task executor runs separate OS processes per worker, each configuring its tokenizer once per task. - **WordNet limitation**: WordNet only has English lemma data. For non-English languages, we skip lemmatization and apply Snowball stemming directly. This is standard -- Snowball stemmers are designed to work standalone. - **CJK languages**: Languages without Snowball support (Chinese, Japanese, Korean, etc.) keep the default English stemmer. Harmless because CJK text uses dictionary segmentation, not stemming.
|
@rwb-truelime , We have released Infinity v0.7.0-dev6 and bumped infinity-sdk in Ragflow to v0.7.0-dev6, please update your RAGFlow PR. |
3958ab0 to
047b982
Compare
|
Updated the PR as requested:
The diff is now ~75 lines across 20 files — all just wiring the language parameter through. The actual stemming logic lives in infinity-sdk. |
047b982 to
0aae68e
Compare
|
Conflict arises here. |
|
@copilot resolve the merge conflicts in this pull request |
Pass the KB language setting from task_executor through all parser modules (naive, book, laws, manual, paper, qa, table, presentation, picture, email, audio, one, tag, resume) to the tokenizer functions. This ensures set_language() is called before tokenization so the correct Snowball stemmer (e.g. Dutch instead of English) is used for BM25 index fields (content_ltks, content_sm_ltks).
Add 'Dutch' / 'Nederlands' to LanguageList, LanguageMap, LanguageAbbreviationMap, LanguageTranslationMap, cross-language form field, and en.ts locale strings.
…tion Latin-script languages like Dutch incorrectly got the CJK full-width separator (;) in table chunks because the eng flag is false for all non-English languages. Now checks the explicit language parameter.
0aae68e to
4cdab62
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14140 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
🎉 |
Summary
RagTokenizersupporting 16 languages (Dutch, German, French, Spanish, etc.)languageparameter through the full tokenization pipeline (14 parser modules + task executor)Problem
RAGFlow uses the English Porter stemmer + WordNet lemmatizer for all BM25 tokenization, regardless of the knowledge base language setting. This produces incorrect stems for non-English text. For example:
This degrades BM25 recall for any non-English knowledge base.
Solution
NLTK already ships Snowball stemmers for 16 languages. This PR:
rag/nlp/rag_tokenizer.py: Overridestokenize()withset_language()and_normalize_token()that selects the correct NLTK Snowball stemmer. Falls back to Porter for unmapped languages (Chinese, Japanese, Korean, etc. — these use character-based tokenization anyway).rag/nlp/__init__.py+ 14rag/app/*.pyparsers +rag/svr/task_executor.py: Threads thelanguageparameter throughtokenize(),tokenize_chunks(),tokenize_table(), and all callers.Nederlands) toLanguageList,LanguageMap,LanguageAbbreviationMap,LanguageTranslationMap, cross-language form field, anden.tslocale.Backward Compatibility
"English", preserving existing behavior for all current users