Repository navigation
fix: correct model type mappings and improve system setting persistence - #16501
Conversation
📝 WalkthroughWalkthroughThe change renames ChangesModel type migration
Estimated code review effort: 3 (Moderate) | ~30 minutes Sequence Diagram(s)sequenceDiagram
participant ModelMetadata
participant TenantModelService
participant API
participant ModelConsumer
ModelMetadata->>TenantModelService: classify model as asr or vision
TenantModelService->>API: expose renamed model type
API->>TenantModelService: resolve tenant default model
TenantModelService->>ModelConsumer: return ASR or vision configuration
ModelConsumer->>ModelConsumer: execute transcription or vision processing
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
|
Warning Tools execution failed with the following error: Failed to run tools: 13 INTERNAL: Received RST_STREAM with code 2 (Internal server error) 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: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/pages/user-setting/setting-model/components/system-setting.tsx (1)
104-122: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDon’t persist the selection locally before the API write succeeds.
Line 107 updates
persistedValuesbeforesetDefaultModelcompletes. If that request fails,getValue()will keep preferring the unsaved local value overdefaultModelDictionary, so the UI shows a setting the backend never stored.Suggested fix
const handleFieldChange = useCallback( async (field: string, value: string) => { - // Update local state immediately so selection shows right away and persists - setPersistedValues((prev) => ({ ...prev, [field]: value || '' })); + const nextValue = value || ''; const modelType = FieldToModelType[field]; if (!modelType) return; if (!value) { await setDefaultModel({ @@ } else { const parsed = parseModelValue(value); if (!parsed) return; await setDefaultModel({ ...parsed, model_type: modelType }); } + + setPersistedValues((prev) => ({ ...prev, [field]: nextValue })); }, [setDefaultModel], );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/setting-model/components/system-setting.tsx` around lines 104 - 122, The local selection is being written to persistedValues in handleFieldChange before setDefaultModel succeeds, which can leave getValue preferring an unsaved value. Update handleFieldChange in system-setting.tsx so the local cache is only merged after the setDefaultModel call completes successfully, and avoid mutating persistedValues when the API request fails or parsing returns early.
🧹 Nitpick comments (1)
web/src/components/ui/modal/modal.tsx (1)
1-1: 📐 Maintainability & Code Quality | 🔵 TrivialRevert modification to
src/components/ui/file.Path instructions prohibit modifying any file under
src/components/ui/including subfolders; modifications require explicit user approval. As per path instructions, "Do not modify, refactor, restyle, or improve any file undersrc/components/ui/including subfolders." This change adds a file header comment tomodal.tsx, which is a modification to a protected path. Please revert or confirm explicit approval was obtained.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/ui/modal/modal.tsx` at line 1, Revert the change in modal.tsx under the protected src/components/ui/ area by removing the added file header comment and restoring the file to its prior state; this is a direct modification of a restricted UI component path, so the update should be undone unless explicit approval exists. Use the modal.tsx file and its top-level module content as the target for the rollback.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/components/llm-select/next.tsx`:
- Around line 40-50: The `ttsModel` memo in `next.tsx` is exposing the wrong
model family for `showSpeech2TextModel`, so update the logic to append the ASR
family instead of TTS. Adjust the `useMemo` that defines `ttsModel` and keep the
`modelTypes` composition unchanged so the `filter` branches still spread the
corrected family for `LlmModelType.Image2text` and the default case.
In `@web/src/pages/user-setting/setting-model/components/system-setting.tsx`:
- Around line 132-135: The getValue callback in system-setting.tsx is treating
empty strings as missing values because it uses ||, which causes cleared
persisted fields to fall back to defaultModelDictionary and repopulate stale
data. Update getValue to check whether the field key exists in persistedValues
first, and only use defaultModelDictionary when the key is absent; keep the
existing fallback to '' for missing keys. Refer to getValue, persistedValues,
and defaultModelDictionary when making the change.
---
Outside diff comments:
In `@web/src/pages/user-setting/setting-model/components/system-setting.tsx`:
- Around line 104-122: The local selection is being written to persistedValues
in handleFieldChange before setDefaultModel succeeds, which can leave getValue
preferring an unsaved value. Update handleFieldChange in system-setting.tsx so
the local cache is only merged after the setDefaultModel call completes
successfully, and avoid mutating persistedValues when the API request fails or
parsing returns early.
---
Nitpick comments:
In `@web/src/components/ui/modal/modal.tsx`:
- Line 1: Revert the change in modal.tsx under the protected src/components/ui/
area by removing the added file header comment and restoring the file to its
prior state; this is a direct modification of a restricted UI component path, so
the update should be undone unless explicit approval exists. Use the modal.tsx
file and its top-level module content as the target for the rollback.
🪄 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: 18937d06-92b2-4037-b352-9077e944a4ec
📒 Files selected for processing (9)
api/apps/services/models_api_service.pyinternal/dao/tenant.gointernal/service/tenant.goweb/src/components/llm-select/next.tsxweb/src/components/model-tree-select.tsxweb/src/components/ui/modal/modal.tsxweb/src/constants/llm.tsweb/src/pages/agent/form/agent-form/index.tsxweb/src/pages/user-setting/setting-model/components/system-setting.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
web/src/constants/knowledge.ts (1)
74-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCentralize the duplicated
LlmModelTypeenum.
web/src/components/llm-select/next.tsxhas the same enum shape. Import this shared enum there instead of maintaining another copy, so future model-type renames don’t require synchronized edits.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/constants/knowledge.ts` around lines 74 - 82, The LlmModelType enum is duplicated, so update web/src/components/llm-select/next.tsx to import and use the shared LlmModelType from knowledge.ts instead of defining its own copy. Keep the enum source of truth in LlmModelType and replace any local references in the llm-select component with the shared symbol so future model-type changes only need one edit.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@web/src/constants/knowledge.ts`:
- Around line 74-82: The LlmModelType enum is duplicated, so update
web/src/components/llm-select/next.tsx to import and use the shared LlmModelType
from knowledge.ts instead of defining its own copy. Keep the enum source of
truth in LlmModelType and replace any local references in the llm-select
component with the shared symbol so future model-type changes only need one
edit.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8ed0786d-72ea-4620-a5c8-e67ce55fad31
📒 Files selected for processing (6)
api/db/services/tenant_llm_service.pycommon/constants.pyconf/llm_factories.jsoninternal/entity/types.goweb/src/components/llm-select/next.tsxweb/src/constants/knowledge.ts
✅ Files skipped from review due to trivial changes (1)
- api/db/services/tenant_llm_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/components/llm-select/next.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)
555-555: 🧹 Nitpick | 🔵 TrivialFix Ruff B009: replace
getattrwith direct attribute access.Since
hasattralready confirmed the attribute exists, usecallable(self.mdl.close)instead ofcallable(getattr(self.mdl, "close")). As per coding guidelines, the project usesrufffor Python linting and formatting, so this should be corrected to keep the codebase clean.🔧 Proposed fix
- if self.mdl and hasattr(self.mdl, "close") and callable(getattr(self.mdl, "close")): + if self.mdl and hasattr(self.mdl, "close") and callable(self.mdl.close):🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/services/tenant_llm_service.py` at line 555, The Ruff B009 issue is in the `tenant_llm_service` close-check where `getattr(self.mdl, "close")` is used after `hasattr` already verified the attribute exists. Update the `self.mdl` close guard to use direct attribute access with `callable(self.mdl.close)` in the same conditional, keeping the existing `close`-handling logic intact and aligned with the project’s linting rules.Sources: Coding guidelines, Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@api/db/services/tenant_llm_service.py`:
- Line 555: The Ruff B009 issue is in the `tenant_llm_service` close-check where
`getattr(self.mdl, "close")` is used after `hasattr` already verified the
attribute exists. Update the `self.mdl` close guard to use direct attribute
access with `callable(self.mdl.close)` in the same conditional, keeping the
existing `close`-handling logic intact and aligned with the project’s linting
rules.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 5f64beae-95a4-4b59-a503-4b9d3258c859
📒 Files selected for processing (2)
api/db/services/tenant_llm_service.pyconf/llm_factories.json
🚧 Files skipped from review as they are similar to previous changes (1)
- conf/llm_factories.json
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16501 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Merge after 0.27.0 from comment of @Lynn-Inf |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)
201-204: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider updating the IMAGE2TEXT error log to match the normalized
"vision"type.Line 201 checks
LLMType.IMAGE2TEXT.value(now"vision"), but the log at Line 203 still reads"Factory not in cv model". For consistency with the taxonomy normalization, consider aligning this message with the"vision"terminology used elsewhere.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/services/tenant_llm_service.py` around lines 201 - 204, The IMAGE2TEXT branch in tenant_llm_service’s model selection still logs legacy “cv model” terminology, which is inconsistent with the normalized vision taxonomy. Update the logging in the LLMType.IMAGE2TEXT.value path to use “vision” wording instead of “cv model”, keeping the supported factories list intact, so the message matches the rest of the model_type normalization in tenant_llm_service.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/db/services/tenant_llm_service.py`:
- Line 555: The `tenant_llm_service.py` close guard is triggering Ruff B009
because `getattr` is unnecessary after the `hasattr` check. Update the
`self.mdl` cleanup logic in the method containing the `self.mdl and
hasattr(self.mdl, "close")` condition to call `self.mdl.close` directly in the
`callable` check instead of using `getattr`, keeping the same safety guard and
behavior.
---
Nitpick comments:
In `@api/db/services/tenant_llm_service.py`:
- Around line 201-204: The IMAGE2TEXT branch in tenant_llm_service’s model
selection still logs legacy “cv model” terminology, which is inconsistent with
the normalized vision taxonomy. Update the logging in the
LLMType.IMAGE2TEXT.value path to use “vision” wording instead of “cv model”,
keeping the supported factories list intact, so the message matches the rest of
the model_type normalization in tenant_llm_service.
🪄 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: ffbbb1b4-4111-42b6-8a37-9273b7e4887c
📒 Files selected for processing (2)
api/db/services/tenant_llm_service.pyconf/llm_factories.json
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)
201-204: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider updating the IMAGE2TEXT error log to match the normalized
"vision"type.Line 201 checks
LLMType.IMAGE2TEXT.value(now"vision"), but the log at Line 203 still reads"Factory not in cv model". For consistency with the taxonomy normalization, consider aligning this message with the"vision"terminology used elsewhere.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/services/tenant_llm_service.py` around lines 201 - 204, The IMAGE2TEXT branch in tenant_llm_service’s model selection still logs legacy “cv model” terminology, which is inconsistent with the normalized vision taxonomy. Update the logging in the LLMType.IMAGE2TEXT.value path to use “vision” wording instead of “cv model”, keeping the supported factories list intact, so the message matches the rest of the model_type normalization in tenant_llm_service.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/db/services/tenant_llm_service.py`:
- Line 555: The `tenant_llm_service.py` close guard is triggering Ruff B009
because `getattr` is unnecessary after the `hasattr` check. Update the
`self.mdl` cleanup logic in the method containing the `self.mdl and
hasattr(self.mdl, "close")` condition to call `self.mdl.close` directly in the
`callable` check instead of using `getattr`, keeping the same safety guard and
behavior.
---
Nitpick comments:
In `@api/db/services/tenant_llm_service.py`:
- Around line 201-204: The IMAGE2TEXT branch in tenant_llm_service’s model
selection still logs legacy “cv model” terminology, which is inconsistent with
the normalized vision taxonomy. Update the logging in the
LLMType.IMAGE2TEXT.value path to use “vision” wording instead of “cv model”,
keeping the supported factories list intact, so the message matches the rest of
the model_type normalization in tenant_llm_service.
🪄 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: ffbbb1b4-4111-42b6-8a37-9273b7e4887c
📒 Files selected for processing (2)
api/db/services/tenant_llm_service.pyconf/llm_factories.json
🛑 Comments failed to post (1)
api/db/services/tenant_llm_service.py (1)
555-555: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Replace
getattrwith direct attribute access to fix Ruff B009.After the
hasattrguard,self.mdl.closeis safe to use directly. As per coding guidelines, userufffor Python linting and formatting.🛠️ Proposed fix
- if self.mdl and hasattr(self.mdl, "close") and callable(getattr(self.mdl, "close")): + if self.mdl and hasattr(self.mdl, "close") and callable(self.mdl.close):📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if self.mdl and hasattr(self.mdl, "close") and callable(self.mdl.close):🧰 Tools
🪛 Ruff (0.15.20)
[warning] 555-555: Do not call
getattrwith a constant attribute value. It is not any safer than normal property access.Replace
getattrwith attribute access(B009)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/services/tenant_llm_service.py` at line 555, The `tenant_llm_service.py` close guard is triggering Ruff B009 because `getattr` is unnecessary after the `hasattr` check. Update the `self.mdl` cleanup logic in the method containing the `self.mdl and hasattr(self.mdl, "close")` condition to call `self.mdl.close` directly in the `callable` check instead of using `getattr`, keeping the same safety guard and behavior.Sources: Coding guidelines, Linters/SAST tools
ec49890 to
08789f0
Compare
08789f0 to
42d11e0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
api/apps/services/models_api_service.py (2)
293-293: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse explicit
str | Noneinstead of implicitOptional.Ruff RUF013 flags
model_type_filter: str = Noneas implicit Optional. Per the project's Python 3.13+ target, prefer the modern union syntax.-def list_tenant_added_models(tenant_id: str, model_type_filter: str = None): +def list_tenant_added_models(tenant_id: str, model_type_filter: str | None = None):🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/services/models_api_service.py` at line 293, Update the list_tenant_added_models signature to annotate model_type_filter explicitly as str | None while preserving its default value and existing behavior.Sources: Coding guidelines, Linters/SAST tools
244-244: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUnused variable
tenantinset_tenant_default_models.Ruff RUF059 flags the unpacked
tenantvariable as never used. Prefix with_to suppress the warning.- e, tenant = TenantService.get_by_id(tenant_id) + e, _tenant = TenantService.get_by_id(tenant_id)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/services/models_api_service.py` at line 244, Update the unpacking in set_tenant_default_models to bind the unused tenant result from TenantService.get_by_id to a name prefixed with an underscore, while preserving the existing use of e and surrounding behavior.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/services/models_api_service.py`:
- Around line 53-54: Update the shared model-type definitions in
common.constants.LLMType and ModelTypeBinary, along with get_model_type_human(),
calculate_model_type(), and remaining callers, to use the renamed asr and vision
values consistently. Replace legacy speech2text/image2text references while
preserving existing model-type mapping and checks.
---
Nitpick comments:
In `@api/apps/services/models_api_service.py`:
- Line 293: Update the list_tenant_added_models signature to annotate
model_type_filter explicitly as str | None while preserving its default value
and existing behavior.
- Line 244: Update the unpacking in set_tenant_default_models to bind the unused
tenant result from TenantService.get_by_id to a name prefixed with an
underscore, while preserving the existing use of e and surrounding behavior.
🪄 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: e81a4593-0641-4d37-bec0-aae50e10cd7d
📒 Files selected for processing (1)
api/apps/services/models_api_service.py
| "asr": "asr", | ||
| "vision": "vision", |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# 1. Check ModelTypeBinary member names
rg -n 'class ModelTypeBinary' --type py -A 20
# 2. Check MODEL_TYPE_TO_FIELD keys
rg -n 'MODEL_TYPE_TO_FIELD' --type py -A 10
# 3. Check if any callers still pass LLMType.SPEECH2TEXT or "speech2text"/"image2text" as model_type
rg -n 'SPEECH2TEXT\|IMAGE2TEXT\|speech2text\|image2text' --type py -g '!**/models_api_service.py'Repository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate relevant files
git ls-files | rg '^(api/apps/services/models_api_service\.py|common/constants\.py|.*model.*type.*\.py|.*constants.*\.py)$' || true
echo '--- models_api_service.py outline ---'
ast-grep outline api/apps/services/models_api_service.py --view expanded || true
echo '--- common/constants.py outline ---'
ast-grep outline common/constants.py --view expanded || true
echo '--- search for ModelTypeBinary and MODEL_TYPE_TO_FIELD ---'
rg -n 'ModelTypeBinary|MODEL_TYPE_TO_FIELD|MODEL_TYPE_TO_TENANT_ID_FIELD|MODEL_TAG_TO_TYPE|LLMType' api common -g '*.py' || true
echo '--- specific slices ---'
sed -n '1,220p' api/apps/services/models_api_service.py || true
echo '--- common/constants.py ---'
sed -n '1,260p' common/constants.py || trueRepository: infiniflow/ragflow
Length of output: 43413
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- api/utils/model_utils.py ---'
sed -n '1,120p' api/utils/model_utils.py
echo '--- tenant_model_service model_type writes/reads ---'
rg -n 'model_type|get_model_type_human|calculate_model_type|ModelTypeBinary' api/db/services/tenant_model_service.py api/db/joint_services/tenant_model_service.py api -g '*.py' | sed -n '1,200p'Repository: infiniflow/ragflow
Length of output: 24981
Keep the model-type rename consistent
MODEL_TAG_TO_TYPE now emits asr / vision, but common.constants.LLMType and ModelTypeBinary still use speech2text / image2text, so get_model_type_human() and calculate_model_type() keep returning the old names. That leaves ASR/vision model checks out of sync until the shared enums/utilities and remaining callers are updated together.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/apps/services/models_api_service.py` around lines 53 - 54, Update the
shared model-type definitions in common.constants.LLMType and ModelTypeBinary,
along with get_model_type_human(), calculate_model_type(), and remaining
callers, to use the renamed asr and vision values consistently. Replace legacy
speech2text/image2text references while preserving existing model-type mapping
and checks.
Align common.constants.LLMType / ModelTypeBinary, common.settings, api/utils/model_utils, and all runtime/test callers to use the asr/vision names emitted by MODEL_TAG_TO_TYPE. Keeps legacy strings only in mysql_migration.py (historical DB migration) and benchmark CLI env/args for external compatibility.
ee86bed to
833b1b1
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (1)
web/src/components/llm-select/next.tsx (1)
42-54: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
showSpeech2TextModelstill maps to['tts']instead of['asr'].This was previously flagged and marked addressed, but the current code still returns
['tts']whenshowSpeech2TextModelis true. Speech-to-text models are identified asasrin the migrated backend, so callers enabling this prop will see TTS models instead of ASR models.🐛 Proposed fix
- const ttsModel = useMemo(() => { - return showSpeech2TextModel ? ['tts'] : []; - }, [showSpeech2TextModel]); + const asrModel = useMemo(() => { + return showSpeech2TextModel ? ['asr'] : []; + }, [showSpeech2TextModel]); const modelTypes = useMemo(() => { if (filter === LlmModelType.Chat) { return ['chat']; } else if (filter === LlmModelType.Image2text) { - return ['vision', ...ttsModel]; + return ['vision', ...asrModel]; } else { - return ['chat', 'vision', ...ttsModel]; + return ['chat', 'vision', ...asrModel]; } - }, [filter, ttsModel]); + }, [filter, asrModel]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/llm-select/next.tsx` around lines 42 - 54, Update the showSpeech2TextModel mapping in the ttsModel useMemo to return the backend’s ASR model type, ['asr'], instead of ['tts']; leave the surrounding modelTypes filtering behavior unchanged.
🧹 Nitpick comments (2)
common/settings.py (1)
262-274: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog the new vision-model initialization path.
Add a safe debug record indicating whether the vision configuration resolved successfully; do not log API keys or full credentials.
Suggested change
VISION_CFG = _resolve_per_model_config(vision_entry, LLM_FACTORY, API_KEY, LLM_BASE_URL) + logging.debug("Resolved vision model configuration: configured=%s", bool(VISION_CFG.get("model")))As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@common/settings.py` around lines 262 - 274, Update the vision-model initialization in the configuration setup, specifically after assigning VISION_CFG via _resolve_per_model_config, to emit a safe debug log indicating whether the vision configuration resolved successfully. Use the existing logging mechanism and include only status or non-sensitive model metadata; never log API keys, credentials, or the full configuration.Source: Coding guidelines
agent/component/llm.py (1)
321-323: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a diagnostic log for the image-to-vision route.
This branch changes model selection when images are present but provides no routing signal. Add a debug log after resolving
model_type, without logging image data or credentials, so model-selection failures are diagnosable.As per coding guidelines,
**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/component/llm.py` around lines 321 - 323, Add a debug-level diagnostic log in the image-to-vision routing branch after model_type is set to LLMType.VISION.value, using the existing logger and reporting only safe model-selection context; do not include image contents or credentials. Keep the resolve_model_type call and routing behavior unchanged.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@common/constants.py`:
- Around line 89-90: Before changing the emitted values for LLMType.ASR and
LLMType.VISION, add migration or normalization for existing model_type data so
legacy "speech2text" and "image2text" values map to "asr" and "vision". Update
the backend’s direct model_type comparisons and catalog/data migration path to
use the normalized values, preserving routing for existing and newly emitted
types.
In `@rag/app/naive.py`:
- Around line 162-167: Update the VISION fallback handling around
get_tenant_default_model_by_type and LLMBundle to catch only expected
lookup/configuration misses, such as LookupError. Do not swallow AssertionError
or other unexpected bundle-construction failures; allow them to propagate while
preserving the existing skip-and-log behavior for the expected missing-model
case.
In `@web/src/components/ui/modal/modal.tsx`:
- Line 5: Revert the unrelated import-only change in the modal component,
restoring the original React import and leaving the protected UI file otherwise
unchanged.
In `@web/src/pages/user-setting/setting-model/layout/system-setting.tsx`:
- Line 32: Update STORAGE_KEY and the associated persistence/state logic in the
system settings component so stored model IDs are scoped to the active
tenant/user rather than shared origin-wide. Recompute the storage key and reset
or reload state when the tenant/user scope changes, ensuring the current API
defaults are used instead of selections from the previous scope.
- Around line 43-50: Update loadPersistedValues to validate the parsed
localStorage payload before returning it: only accept a non-null object whose
values are strings, otherwise return an empty record. Preserve the existing
fallback for missing or invalid storage data so persistedValues[field] and
ModelTreeSelect always receive safe string values.
- Around line 108-123: The handleFieldChange flow in useSetDefaultModel
currently persists persistedValues before the mutation succeeds; update it to
save the selected field only after a successful response with data.code === 0.
On request rejection or any nonzero response code, avoid or roll back the
optimistic persistedValues update so localStorage never retains an unsaved model
ID.
---
Duplicate comments:
In `@web/src/components/llm-select/next.tsx`:
- Around line 42-54: Update the showSpeech2TextModel mapping in the ttsModel
useMemo to return the backend’s ASR model type, ['asr'], instead of ['tts'];
leave the surrounding modelTypes filtering behavior unchanged.
---
Nitpick comments:
In `@agent/component/llm.py`:
- Around line 321-323: Add a debug-level diagnostic log in the image-to-vision
routing branch after model_type is set to LLMType.VISION.value, using the
existing logger and reporting only safe model-selection context; do not include
image contents or credentials. Keep the resolve_model_type call and routing
behavior unchanged.
In `@common/settings.py`:
- Around line 262-274: Update the vision-model initialization in the
configuration setup, specifically after assigning VISION_CFG via
_resolve_per_model_config, to emit a safe debug log indicating whether the
vision configuration resolved successfully. Use the existing logging mechanism
and include only status or non-sensitive model metadata; never log API keys,
credentials, or the full configuration.
🪄 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: 423d5239-4904-4e7a-8380-16efaa7b4a5e
📒 Files selected for processing (42)
admin/server/auth.pyagent/component/llm.pyapi/apps/llm_app.pyapi/apps/restful_apis/chat_api.pyapi/apps/restful_apis/openai_api.pyapi/apps/restful_apis/user_api.pyapi/apps/services/models_api_service.pyapi/db/db_models.pyapi/db/init_data.pyapi/db/joint_services/tenant_model_service.pyapi/db/joint_services/user_account_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pycommon/constants.pycommon/settings.pydeepdoc/parser/figure_parser.pydeepdoc/parser/mineru_parser.pyinternal/dao/tenant.gointernal/service/tenant.gorag/app/audio.pyrag/app/naive.pyrag/app/picture.pyrag/flow/parser/parser.pyrag/flow/parser/utils.pyrag/llm/cv_model.pyrag/llm/model_meta.pyrag/prompts/generator.pytest/testcases/restful_api/test_chats.pytest/testcases/restful_api/test_user_tenant_routes_unit.pytest/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.pytest/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.pytest/testcases/test_web_api/test_llm_app/test_llm_list_unit.pytest/testcases/test_web_api/test_user_app/test_user_app_unit.pytest/unit_test/api/apps/services/test_delete_datasets.pytest/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.pyweb/src/components/llm-select/next.tsxweb/src/components/model-tree-select.tsxweb/src/components/ui/modal/modal.tsxweb/src/constants/llm.tsweb/src/pages/agent/form/agent-form/index.tsxweb/src/pages/user-setting/setting-model/layout/system-setting.tsx
🚧 Files skipped from review as they are similar to previous changes (6)
- web/src/components/model-tree-select.tsx
- internal/dao/tenant.go
- web/src/pages/agent/form/agent-form/index.tsx
- web/src/constants/llm.ts
- internal/service/tenant.go
- api/apps/services/models_api_service.py
| if "vision_model" not in kwargs: | ||
| try: | ||
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.IMAGE2TEXT) | ||
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION) | ||
| kwargs["vision_model"] = LLMBundle(tenant_id=tenant_id, model_config=vision_model_config, lang=lang) | ||
| except Exception as vlm_err: | ||
| logging.info(f"[MinerU] no IMAGE2TEXT model for tenant; skipping image VLM enhancement: {vlm_err}") | ||
| logging.info(f"[MinerU] no VISION model for tenant; skipping image VLM enhancement: {vlm_err}") |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
sed -n '130,190p' rag/app/naive.pyRepository: infiniflow/ragflow
Length of output: 2726
🏁 Script executed:
rg -n "def get_tenant_default_model_by_type|class LLMBundle|LLMType.VISION|except Exception as vlm_err" -S ragRepository: infiniflow/ragflow
Length of output: 2457
🏁 Script executed:
sed -n '1,260p' rag/llm/utils.pyRepository: infiniflow/ragflow
Length of output: 216
🏁 Script executed:
sed -n '1,260p' rag/llm/__init__.pyRepository: infiniflow/ragflow
Length of output: 8255
🏁 Script executed:
rg -n "def get_tenant_default_model_by_type|def resolve_model_config|class LLMBundle" rag -SRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
rg -n "get_tenant_default_model_by_type|resolve_model_config|class LLMBundle" -S .Repository: infiniflow/ragflow
Length of output: 38093
🏁 Script executed:
fd -a "model_utils.py|bundle.py|llm*.py|tenant*.py" .Repository: infiniflow/ragflow
Length of output: 312
🏁 Script executed:
sed -n '1,340p' api/db/joint_services/tenant_model_service.pyRepository: infiniflow/ragflow
Length of output: 14620
🏁 Script executed:
sed -n '1,240p' api/utils/model_utils.pyRepository: infiniflow/ragflow
Length of output: 1388
🏁 Script executed:
sed -n '1,220p' api/db/services/llm_service.pyRepository: infiniflow/ragflow
Length of output: 10106
🏁 Script executed:
rg -n "class LLMBundle|def __init__|raise LookupError|raise Exception" api/db/services/llm_service.py -nRepository: infiniflow/ragflow
Length of output: 277
🏁 Script executed:
sed -n '340,390p' rag/app/naive.pyRepository: infiniflow/ragflow
Length of output: 1926
🏁 Script executed:
sed -n '1060,1095p' rag/app/naive.pyRepository: infiniflow/ragflow
Length of output: 1799
🏁 Script executed:
sed -n '1,220p' deepdoc/parser/figure_parser.pyRepository: infiniflow/ragflow
Length of output: 9349
🏁 Script executed:
rg -n "class LLM4Tenant|def __init__" api/db/services/tenant_llm_service.py -nRepository: infiniflow/ragflow
Length of output: 268
🏁 Script executed:
sed -n '1,260p' api/db/services/tenant_llm_service.pyRepository: infiniflow/ragflow
Length of output: 11883
🏁 Script executed:
sed -n '506,720p' api/db/services/tenant_llm_service.pyRepository: infiniflow/ragflow
Length of output: 3388
🏁 Script executed:
python3 - <<'PY'
from pathlib import Path
text = Path("api/db/services/tenant_llm_service.py").read_text()
for needle in ["class LLM4Tenant", "def __init__", "raise LookupError", "raise Exception", "Factory not in", "model_instance"]:
print(f"{needle}: {text.find(needle)}")
PYRepository: infiniflow/ragflow
Length of output: 286
Narrow the VISION fallback exception rag/app/naive.py:162-167 should only fall back on expected lookup/configuration misses. except Exception also hides AssertionError from LLMBundle(...) when no model instance is created, along with other setup bugs, and turns them into a silent “no vision model” path. Catch LookupError here, or split model lookup from bundle creation and let unexpected failures surface.
🧰 Tools
🪛 Ruff (0.15.20)
[warning] 166-166: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/app/naive.py` around lines 162 - 167, Update the VISION fallback handling
around get_tenant_default_model_by_type and LLMBundle to catch only expected
lookup/configuration misses, such as LookupError. Do not swallow AssertionError
or other unexpected bundle-construction failures; allow them to propagate while
preserving the existing skip-and-log behavior for the expected missing-model
case.
Source: Linters/SAST tools
| import { cn } from '@/lib/utils'; | ||
| import * as DialogPrimitive from '@radix-ui/react-dialog'; | ||
| import { AlertCircle, CheckCircle, Info, Loader, X } from 'lucide-react'; | ||
| import React, { FC, ReactNode, useCallback, useEffect, useMemo } from 'react'; |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Revert this unrelated change.
This import-only edit has no functional benefit and modifies a protected src/components/ui/ file. Please restore the file unless explicit approval was granted.
As per coding guidelines, files under web/src/components/ui/**/*.{ts,tsx} must not be modified without explicit approval.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/components/ui/modal/modal.tsx` at line 5, Revert the unrelated
import-only change in the modal component, restoring the original React import
and leaving the protected UI file otherwise unchanged.
Source: Coding guidelines
| import { useCallback, useMemo } from 'react'; | ||
| import { useCallback, useEffect, useMemo, useState } from 'react'; | ||
|
|
||
| const STORAGE_KEY = 'ragflow-system-model-settings'; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Scope persisted values to the active tenant/user.
STORAGE_KEY is origin-wide, but the stored values are tenant-specific model IDs. Switching accounts or tenants in the same browser will load the previous tenant’s selections before the current API defaults, causing stale or invalid models to appear. Include the active tenant/user in the key and reset state when that scope changes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/user-setting/setting-model/layout/system-setting.tsx` at line
32, Update STORAGE_KEY and the associated persistence/state logic in the system
settings component so stored model IDs are scoped to the active tenant/user
rather than shared origin-wide. Recompute the storage key and reset or reload
state when the tenant/user scope changes, ensuring the current API defaults are
used instead of selections from the previous scope.
| /** Read persisted model selections from localStorage */ | ||
| function loadPersistedValues(): Record<string, string> { | ||
| try { | ||
| const raw = localStorage.getItem(STORAGE_KEY); | ||
| return raw ? JSON.parse(raw) : {}; | ||
| } catch { | ||
| return {}; | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Validate the persisted payload shape before returning it.
The type annotation does not validate JSON.parse. If storage contains null, loadPersistedValues() returns null, and persistedValues[field] later crashes during render. Non-string values can also be passed to ModelTreeSelect.
Suggested fix
function loadPersistedValues(): Record<string, string> {
try {
const raw = localStorage.getItem(STORAGE_KEY);
- return raw ? JSON.parse(raw) : {};
+ if (!raw) return {};
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(parsed).filter(([, value]) => typeof value === 'string'),
+ );
} catch {
return {};
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** Read persisted model selections from localStorage */ | |
| function loadPersistedValues(): Record<string, string> { | |
| try { | |
| const raw = localStorage.getItem(STORAGE_KEY); | |
| return raw ? JSON.parse(raw) : {}; | |
| } catch { | |
| return {}; | |
| } | |
| /** Read persisted model selections from localStorage */ | |
| function loadPersistedValues(): Record<string, string> { | |
| try { | |
| const raw = localStorage.getItem(STORAGE_KEY); | |
| if (!raw) return {}; | |
| const parsed: unknown = JSON.parse(raw); | |
| if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { | |
| return {}; | |
| } | |
| return Object.fromEntries( | |
| Object.entries(parsed).filter(([, value]) => typeof value === 'string'), | |
| ); | |
| } catch { | |
| return {}; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/user-setting/setting-model/layout/system-setting.tsx` around
lines 43 - 50, Update loadPersistedValues to validate the parsed localStorage
payload before returning it: only accept a non-null object whose values are
strings, otherwise return an empty record. Preserve the existing fallback for
missing or invalid storage data so persistedValues[field] and ModelTreeSelect
always receive safe string values.
| // Local state synced with localStorage for persistence across page refreshes. | ||
| // This handles the case where the Go backend hasn't been rebuilt yet and | ||
| // doesn't return TTS/ASR/VLM defaults from the API (same pattern as ASR/VLM). | ||
| const [persistedValues, setPersistedValues] = | ||
| useState<Record<string, string>>(loadPersistedValues); | ||
|
|
||
| // Sync localStorage whenever persistedValues changes | ||
| useEffect(() => { | ||
| savePersistedValues(persistedValues); | ||
| }, [persistedValues]); | ||
|
|
||
| const handleFieldChange = useCallback( | ||
| async (field: string, value: string) => { | ||
| // Update local state immediately so selection shows right away and persists | ||
| setPersistedValues((prev) => ({ ...prev, [field]: value || '' })); | ||
|
|
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the target component around the cited lines.
sed -n '1,220p' web/src/pages/user-setting/setting-model/layout/system-setting.tsx
printf '\n---\n'
# Find the backend update hook/function and its callers.
rg -n "setDefaultModel|persistedValues|savePersistedValues|loadPersistedValues|handleFieldChange" web/src -S
printf '\n---\n'
# Show the implementation of setDefaultModel and its error contract.
rg -n "export .*setDefaultModel|const .*setDefaultModel|function .*setDefaultModel" web/src -SRepository: infiniflow/ragflow
Length of output: 8872
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the mutation hook implementation and its error handling.
sed -n '600,690p' web/src/hooks/use-llm-request.tsx
printf '\n---\n'
# Inspect the service method contract used by the hook.
sed -n '1,140p' web/src/services/llm-service.tsRepository: infiniflow/ragflow
Length of output: 3633
Persist only after setDefaultModel succeeds. The optimistic persistedValues update runs before the mutation, and useSetDefaultModel only treats data.code === 0 as success. If the request rejects or returns a nonzero code, localStorage still stores the unsaved model ID and refreshes will prefer it over the API value. Roll back on failure or save only after success.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/user-setting/setting-model/layout/system-setting.tsx` around
lines 108 - 123, The handleFieldChange flow in useSetDefaultModel currently
persists persistedValues before the mutation succeeds; update it to save the
selected field only after a successful response with data.code === 0. On request
rejection or any nonzero response code, avoid or roll back the optimistic
persistedValues update so localStorage never retains an unsaved model ID.
… rename Add startup data migration in api/db/db_models.py.migrate_db() to rename speech2text/image2text to asr/vision in llm and tenant_llm tables. Make api/utils/model_utils.calculate_model_type() accept the legacy aliases defensively. Update tools/scripts/mysql_migration.py mappings so the standalone migration script also recognizes asr/vision alongside the legacy names.
d4e6fcc to
2956b9b
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/db/db_models.py (1)
1838-1876: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd
# noqa: S608to suppress false-positive SQL injection lint.The table name in the
UPDATEstatement is interpolated via.format(table), buttablecomes from a hardcoded list (["llm", "tenant_llm"]) and the actual values are properly parameterized with%s. This is safe, but Ruff S608 will flag it on every run. Adding a targetednoqakeeps the lint clean without restructuring.The broad
except Exceptionat line 1869 is acceptable for migration resilience — the warning log preserves diagnosability — but if you want stricter handling, catchingOperationalError, ProgrammingError(as done in the legacy index drop above) would be more consistent with the rest ofmigrate_db.♻️ Suggested noqa annotation
- cursor = DB.execute_sql( - "UPDATE {} SET model_type = %s WHERE model_type = %s".format(table), + cursor = DB.execute_sql( # noqa: S608 # table name is from a hardcoded list + "UPDATE {} SET model_type = %s WHERE model_type = %s".format(table),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/db_models.py` around lines 1838 - 1876, Add a targeted # noqa: S608 annotation to the dynamically formatted UPDATE statement in migrate_model_type_names, specifically the DB.execute_sql call, to suppress Ruff’s false-positive SQL injection warning while preserving the existing hardcoded table list and parameterized values.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@rag/flow/parser/utils.py`:
- Around line 173-175: Update the vision model resolution flow around
resolve_model_config to normalize the optional vlm_conf before accessing llm_id,
then catch only LookupError for missing model references and fall back to
get_tenant_default_model_by_type. Allow malformed configuration and unexpected
resolution errors to propagate instead of silently selecting the tenant default.
---
Nitpick comments:
In `@api/db/db_models.py`:
- Around line 1838-1876: Add a targeted # noqa: S608 annotation to the
dynamically formatted UPDATE statement in migrate_model_type_names, specifically
the DB.execute_sql call, to suppress Ruff’s false-positive SQL injection warning
while preserving the existing hardcoded table list and parameterized values.
🪄 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: 9d8e3df5-5960-4eb8-9f67-d2a5316565cf
📒 Files selected for processing (44)
admin/server/auth.pyagent/component/llm.pyapi/apps/llm_app.pyapi/apps/restful_apis/chat_api.pyapi/apps/restful_apis/openai_api.pyapi/apps/restful_apis/user_api.pyapi/apps/services/models_api_service.pyapi/db/db_models.pyapi/db/init_data.pyapi/db/joint_services/tenant_model_service.pyapi/db/joint_services/user_account_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pyapi/utils/model_utils.pycommon/constants.pycommon/settings.pydeepdoc/parser/figure_parser.pydeepdoc/parser/mineru_parser.pyinternal/dao/tenant.gointernal/service/tenant.gorag/app/audio.pyrag/app/naive.pyrag/app/picture.pyrag/flow/parser/parser.pyrag/flow/parser/utils.pyrag/llm/cv_model.pyrag/llm/model_meta.pyrag/prompts/generator.pytest/testcases/restful_api/test_chats.pytest/testcases/restful_api/test_user_tenant_routes_unit.pytest/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.pytest/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.pytest/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.pytest/testcases/test_web_api/test_llm_app/test_llm_list_unit.pytest/testcases/test_web_api/test_user_app/test_user_app_unit.pytest/unit_test/api/apps/services/test_delete_datasets.pytest/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.pytools/scripts/mysql_migration.pyweb/src/components/llm-select/next.tsxweb/src/components/model-tree-select.tsxweb/src/components/ui/modal/modal.tsxweb/src/constants/llm.tsweb/src/pages/agent/form/agent-form/index.tsxweb/src/pages/user-setting/setting-model/layout/system-setting.tsx
🚧 Files skipped from review as they are similar to previous changes (39)
- rag/app/audio.py
- api/apps/restful_apis/user_api.py
- agent/component/llm.py
- web/src/components/ui/modal/modal.tsx
- api/db/joint_services/user_account_service.py
- web/src/constants/llm.ts
- test/testcases/test_web_api/test_user_app/test_user_app_unit.py
- admin/server/auth.py
- api/apps/services/models_api_service.py
- api/db/init_data.py
- test/testcases/restful_api/test_chats.py
- deepdoc/parser/mineru_parser.py
- api/db/joint_services/tenant_model_service.py
- api/apps/restful_apis/openai_api.py
- api/apps/restful_apis/chat_api.py
- rag/app/picture.py
- web/src/components/model-tree-select.tsx
- rag/prompts/generator.py
- web/src/pages/user-setting/setting-model/layout/system-setting.tsx
- test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
- web/src/components/llm-select/next.tsx
- test/unit_test/api/apps/services/test_delete_datasets.py
- test/testcases/test_web_api/test_llm_app/test_llm_list_unit.py
- internal/dao/tenant.go
- internal/service/tenant.go
- test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
- common/constants.py
- api/apps/llm_app.py
- common/settings.py
- web/src/pages/agent/form/agent-form/index.tsx
- rag/llm/cv_model.py
- api/db/services/tenant_llm_service.py
- deepdoc/parser/figure_parser.py
- rag/llm/model_meta.py
- api/db/services/dialog_service.py
- test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
- test/testcases/restful_api/test_user_tenant_routes_unit.py
- test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
- rag/flow/parser/parser.py
| vision_model_config = resolve_model_config(tenant_id, LLMType.VISION, vlm_conf["llm_id"]) | ||
| except Exception: | ||
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.IMAGE2TEXT) | ||
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Catch only expected model-resolution failures.
resolve_model_config() signals missing model references with LookupError; catching every Exception also treats malformed vlm_conf and unexpected resolution bugs as “use the default model,” silently ignoring explicit configuration. Normalize the optional config first and catch only the expected lookup case.
Proposed fix
- try:
- vision_model_config = resolve_model_config(tenant_id, LLMType.VISION, vlm_conf["llm_id"])
- except Exception:
+ model_id = vlm_conf.get("llm_id") if vlm_conf else None
+ if model_id:
+ try:
+ vision_model_config = resolve_model_config(tenant_id, LLMType.VISION, model_id)
+ except LookupError:
+ vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION)
+ else:
vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| vision_model_config = resolve_model_config(tenant_id, LLMType.VISION, vlm_conf["llm_id"]) | |
| except Exception: | |
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.IMAGE2TEXT) | |
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION) | |
| model_id = vlm_conf.get("llm_id") if vlm_conf else None | |
| if model_id: | |
| try: | |
| vision_model_config = resolve_model_config(tenant_id, LLMType.VISION, model_id) | |
| except LookupError: | |
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION) | |
| else: | |
| vision_model_config = get_tenant_default_model_by_type(tenant_id, LLMType.VISION) |
🧰 Tools
🪛 Ruff (0.15.20)
[warning] 174-174: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/flow/parser/utils.py` around lines 173 - 175, Update the vision model
resolution flow around resolve_model_config to normalize the optional vlm_conf
before accessing llm_id, then catch only LookupError for missing model
references and fall back to get_tenant_default_model_by_type. Allow malformed
configuration and unexpected resolution errors to propagate instead of silently
selecting the tenant default.
Source: Linters/SAST tools
| {findLlmByUuid(llmId)?.model_type?.includes('vision') && ( | ||
| <QueryVariable | ||
| name="visual_files_var" | ||
| label={t('flow.visualInputFile')} |
There was a problem hiding this comment.
Multilingual support is required.
| } | ||
|
|
||
| /** Read persisted model selections from localStorage */ | ||
| function loadPersistedValues(): Record<string, string> { |
There was a problem hiding this comment.
localStorage cannot be used here.
Summary
This PR fixes model type mapping inconsistencies across the backend stack and improves frontend system setting persistence for ASR, TTS, and Vision models.
Backend changes:
models_api_service.py): Corrected ASR model type from"speech2text"to"asr", and Vision model type from"image2text"to"vision"tenant.go): ChangedTTSIDfield from optional pointer (*string) to required value (string) in both DAO and service layers; removed redundant nil check when fetching default TTS modelFrontend changes:
llm-select/next.tsx,model-tree-select.tsx,modal.tsx) to properly handle the corrected ASR/TTS/Vision model typeslocalStoragepersistence for system settings so user selections survive page refreshThese changes ensure consistent model type handling across Python, Go, and TypeScript layers while improving UX by persisting user's model choices.
[ci]