Skip to content

fix: correct model type mappings and improve system setting persistence - #16501

Merged
wangq8 merged 6 commits into
infiniflow:mainfrom
euvre:fix/model-type-mapping-and-persistence
Jul 13, 2026
Merged

wangq8 merged 6 commits into
infiniflow:mainfrom
euvre:fix/model-type-mapping-and-persistence

Conversation

@euvre

@euvre euvre commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

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:

  • Python (models_api_service.py): Corrected ASR model type from "speech2text" to "asr", and Vision model type from "image2text" to "vision"
  • Go (tenant.go): Changed TTSID field from optional pointer (*string) to required value (string) in both DAO and service layers; removed redundant nil check when fetching default TTS model

Frontend changes:

  • Switched API proxy scheme to Go backend in development environment
  • Updated model selection components (llm-select/next.tsx, model-tree-select.tsx, modal.tsx) to properly handle the corrected ASR/TTS/Vision model types
  • Added localStorage persistence for system settings so user selections survive page refresh
  • Implemented proper resolution order: localStorage → API response → empty fallback

These changes ensure consistent model type handling across Python, Go, and TypeScript layers while improving UX by persisting user's model choices.

[ci]

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧰 typescript Pull requests that update Typescript code labels Jun 30, 2026
@euvre euvre added the ci Continue Integration label Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change renames speech2text and image2text model identifiers to asr and vision across backend, frontend, tenant configuration, model consumers, provider inference, and tests. Tenant TTS/OCR IDs also use non-pointer string fields, and system model selections persist locally.

Changes

Model type migration

Layer / File(s) Summary
Type contracts and model configuration
common/*, api/apps/services/*, api/db/*, internal/*, web/src/constants/*, web/src/components/*
Model enums, settings, normalization mappings, tenant mappings, frontend field maps, and tenant identifier fields adopt asr and vision.
Tenant and API routing
api/apps/*, api/db/services/*, api/db/db_models.py
Tenant initialization, validation, default lookup, dispatch, usage accounting, and database migration logic route the renamed model types.
Model consumers and provider inference
agent/*, deepdoc/*, rag/*
Chat, audio, document, media, prompt, and provider-classification paths resolve ASR and vision models through the new identifiers.
Frontend state and test alignment
web/src/pages/*, test/*, tools/scripts/mysql_migration.py
Agent visual-input handling, persisted system model selections, migration mappings, and test fixtures reflect the updated names.

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
Loading

Possibly related PRs

Suggested labels: ☯️ refactor

Suggested reviewers: wangq8

Poem

A rabbit renames types with care,
Asr and vision hop through the air.
Tenant models line up in flight,
Local choices persist just right.
I thump beneath the new model light! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main changes: model type mapping fixes and system setting persistence.
Description check ✅ Passed The description includes the required Summary section with background and a concise overview of backend and frontend changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The head commit changed during the review from 9babb8a to 304aba6.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Don’t persist the selection locally before the API write succeeds.

Line 107 updates persistedValues before setDefaultModel completes. If that request fails, getValue() will keep preferring the unsaved local value over defaultModelDictionary, 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 | 🔵 Trivial

Revert 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 under src/components/ui/ including subfolders." This change adds a file header comment to modal.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

📥 Commits

Reviewing files that changed from the base of the PR and between 3633d08 and 304aba6.

📒 Files selected for processing (9)
  • api/apps/services/models_api_service.py
  • internal/dao/tenant.go
  • internal/service/tenant.go
  • web/src/components/llm-select/next.tsx
  • web/src/components/model-tree-select.tsx
  • web/src/components/ui/modal/modal.tsx
  • web/src/constants/llm.ts
  • web/src/pages/agent/form/agent-form/index.tsx
  • web/src/pages/user-setting/setting-model/components/system-setting.tsx

Comment thread web/src/components/llm-select/next.tsx Resolved
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jul 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
web/src/constants/knowledge.ts (1)

74-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Centralize the duplicated LlmModelType enum.

web/src/components/llm-select/next.tsx has 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

📥 Commits

Reviewing files that changed from the base of the PR and between b49d865 and dff9ce4.

📒 Files selected for processing (6)
  • api/db/services/tenant_llm_service.py
  • common/constants.py
  • conf/llm_factories.json
  • internal/entity/types.go
  • web/src/components/llm-select/next.tsx
  • web/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)

555-555: 🧹 Nitpick | 🔵 Trivial

Fix Ruff B009: replace getattr with direct attribute access.

Since hasattr already confirmed the attribute exists, use callable(self.mdl.close) instead of callable(getattr(self.mdl, "close")). As per coding guidelines, the project uses ruff for 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

📥 Commits

Reviewing files that changed from the base of the PR and between dff9ce4 and 79553b6.

📒 Files selected for processing (2)
  • api/db/services/tenant_llm_service.py
  • conf/llm_factories.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • conf/llm_factories.json

@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (891261e) to head (e28d7e2).
⚠️ Report is 5 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 requested a review from Lynn-Inf July 1, 2026 05:32
@wangq8

wangq8 commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator

Merge after 0.27.0 from comment of @Lynn-Inf

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)

201-204: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between dff9ce4 and 79553b6.

📒 Files selected for processing (2)
  • api/db/services/tenant_llm_service.py
  • conf/llm_factories.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between dff9ce4 and 79553b6.

📒 Files selected for processing (2)
  • api/db/services/tenant_llm_service.py
  • conf/llm_factories.json
🛑 Comments failed to post (1)
api/db/services/tenant_llm_service.py (1)

555-555: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Replace getattr with direct attribute access to fix Ruff B009.

After the hasattr guard, self.mdl.close is safe to use directly. As per coding guidelines, use ruff for 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 getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with 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

@euvre
euvre requested a review from wangq8 July 10, 2026 07:46
@euvre
euvre force-pushed the fix/model-type-mapping-and-persistence branch 3 times, most recently from ec49890 to 08789f0 Compare July 10, 2026 09:52
@euvre
euvre force-pushed the fix/model-type-mapping-and-persistence branch from 08789f0 to 42d11e0 Compare July 10, 2026 10:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
api/apps/services/models_api_service.py (2)

293-293: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use explicit str | None instead of implicit Optional.

Ruff RUF013 flags model_type_filter: str = None as 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 value

Unused variable tenant in set_tenant_default_models.

Ruff RUF059 flags the unpacked tenant variable 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

📥 Commits

Reviewing files that changed from the base of the PR and between 79553b6 and ee86bed.

📒 Files selected for processing (1)
  • api/apps/services/models_api_service.py

Comment on lines +53 to +54
"asr": "asr",
"vision": "vision",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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 || true

Repository: 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.

@Lynn-Inf Lynn-Inf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

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.
@euvre
euvre force-pushed the fix/model-type-mapping-and-persistence branch from ee86bed to 833b1b1 Compare July 13, 2026 03:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

♻️ Duplicate comments (1)
web/src/components/llm-select/next.tsx (1)

42-54: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

showSpeech2TextModel still maps to ['tts'] instead of ['asr'].

This was previously flagged and marked addressed, but the current code still returns ['tts'] when showSpeech2TextModel is true. Speech-to-text models are identified as asr in 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 win

Log 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between ee86bed and d4e6fcc.

📒 Files selected for processing (42)
  • admin/server/auth.py
  • agent/component/llm.py
  • api/apps/llm_app.py
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/openai_api.py
  • api/apps/restful_apis/user_api.py
  • api/apps/services/models_api_service.py
  • api/db/db_models.py
  • api/db/init_data.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/joint_services/user_account_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • common/constants.py
  • common/settings.py
  • deepdoc/parser/figure_parser.py
  • deepdoc/parser/mineru_parser.py
  • internal/dao/tenant.go
  • internal/service/tenant.go
  • rag/app/audio.py
  • rag/app/naive.py
  • rag/app/picture.py
  • rag/flow/parser/parser.py
  • rag/flow/parser/utils.py
  • rag/llm/cv_model.py
  • rag/llm/model_meta.py
  • rag/prompts/generator.py
  • test/testcases/restful_api/test_chats.py
  • test/testcases/restful_api/test_user_tenant_routes_unit.py
  • test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_llm_app/test_llm_list_unit.py
  • test/testcases/test_web_api/test_user_app/test_user_app_unit.py
  • test/unit_test/api/apps/services/test_delete_datasets.py
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
  • web/src/components/llm-select/next.tsx
  • web/src/components/model-tree-select.tsx
  • web/src/components/ui/modal/modal.tsx
  • web/src/constants/llm.ts
  • web/src/pages/agent/form/agent-form/index.tsx
  • web/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

Comment thread common/constants.py Resolved
Comment thread rag/app/naive.py
Comment on lines 162 to +167
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}")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '130,190p' rag/app/naive.py

Repository: 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 rag

Repository: infiniflow/ragflow

Length of output: 2457


🏁 Script executed:

sed -n '1,260p' rag/llm/utils.py

Repository: infiniflow/ragflow

Length of output: 216


🏁 Script executed:

sed -n '1,260p' rag/llm/__init__.py

Repository: infiniflow/ragflow

Length of output: 8255


🏁 Script executed:

rg -n "def get_tenant_default_model_by_type|def resolve_model_config|class LLMBundle" rag -S

Repository: 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.py

Repository: infiniflow/ragflow

Length of output: 14620


🏁 Script executed:

sed -n '1,240p' api/utils/model_utils.py

Repository: infiniflow/ragflow

Length of output: 1388


🏁 Script executed:

sed -n '1,220p' api/db/services/llm_service.py

Repository: infiniflow/ragflow

Length of output: 10106


🏁 Script executed:

rg -n "class LLMBundle|def __init__|raise LookupError|raise Exception" api/db/services/llm_service.py -n

Repository: infiniflow/ragflow

Length of output: 277


🏁 Script executed:

sed -n '340,390p' rag/app/naive.py

Repository: infiniflow/ragflow

Length of output: 1926


🏁 Script executed:

sed -n '1060,1095p' rag/app/naive.py

Repository: infiniflow/ragflow

Length of output: 1799


🏁 Script executed:

sed -n '1,220p' deepdoc/parser/figure_parser.py

Repository: infiniflow/ragflow

Length of output: 9349


🏁 Script executed:

rg -n "class LLM4Tenant|def __init__" api/db/services/tenant_llm_service.py -n

Repository: infiniflow/ragflow

Length of output: 268


🏁 Script executed:

sed -n '1,260p' api/db/services/tenant_llm_service.py

Repository: infiniflow/ragflow

Length of output: 11883


🏁 Script executed:

sed -n '506,720p' api/db/services/tenant_llm_service.py

Repository: 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)}")
PY

Repository: 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';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +43 to +50
/** 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 {};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
/** 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.

Comment on lines +108 to +123
// 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 || '' }));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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 -S

Repository: 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.ts

Repository: 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.
@euvre
euvre force-pushed the fix/model-type-mapping-and-persistence branch from d4e6fcc to 2956b9b Compare July 13, 2026 05:05

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/db/db_models.py (1)

1838-1876: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add # noqa: S608 to suppress false-positive SQL injection lint.

The table name in the UPDATE statement is interpolated via .format(table), but table comes 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 targeted noqa keeps the lint clean without restructuring.

The broad except Exception at line 1869 is acceptable for migration resilience — the warning log preserves diagnosability — but if you want stricter handling, catching OperationalError, ProgrammingError (as done in the legacy index drop above) would be more consistent with the rest of migrate_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

📥 Commits

Reviewing files that changed from the base of the PR and between d4e6fcc and e28d7e2.

📒 Files selected for processing (44)
  • admin/server/auth.py
  • agent/component/llm.py
  • api/apps/llm_app.py
  • api/apps/restful_apis/chat_api.py
  • api/apps/restful_apis/openai_api.py
  • api/apps/restful_apis/user_api.py
  • api/apps/services/models_api_service.py
  • api/db/db_models.py
  • api/db/init_data.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/joint_services/user_account_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • api/utils/model_utils.py
  • common/constants.py
  • common/settings.py
  • deepdoc/parser/figure_parser.py
  • deepdoc/parser/mineru_parser.py
  • internal/dao/tenant.go
  • internal/service/tenant.go
  • rag/app/audio.py
  • rag/app/naive.py
  • rag/app/picture.py
  • rag/flow/parser/parser.py
  • rag/flow/parser/utils.py
  • rag/llm/cv_model.py
  • rag/llm/model_meta.py
  • rag/prompts/generator.py
  • test/testcases/restful_api/test_chats.py
  • test/testcases/restful_api/test_user_tenant_routes_unit.py
  • test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py
  • test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py
  • test/testcases/test_web_api/test_chunk_app/test_chunk_routes_unit.py
  • test/testcases/test_web_api/test_llm_app/test_llm_list_unit.py
  • test/testcases/test_web_api/test_user_app/test_user_app_unit.py
  • test/unit_test/api/apps/services/test_delete_datasets.py
  • test/unit_test/api/apps/services/test_models_api_service_list_tenant_added_models.py
  • tools/scripts/mysql_migration.py
  • web/src/components/llm-select/next.tsx
  • web/src/components/model-tree-select.tsx
  • web/src/components/ui/modal/modal.tsx
  • web/src/constants/llm.ts
  • web/src/pages/agent/form/agent-form/index.tsx
  • web/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

Comment thread rag/flow/parser/utils.py
Comment on lines +173 to +175
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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

@wangq8
wangq8 merged commit 3bfad1f into infiniflow:main Jul 13, 2026
3 of 6 checks passed
{findLlmByUuid(llmId)?.model_type?.includes('vision') && (
<QueryVariable
name="visual_files_var"
label={t('flow.visualInputFile')}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multilingual support is required.

}

/** Read persisted model selections from localStorage */
function loadPersistedValues(): Record<string, string> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

localStorage cannot be used here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files. 🧰 typescript Pull requests that update Typescript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants