Skip to content

Fix: restore saved api_key fallback in add_llm (#14921) - #14941

Merged
KevinHuSh merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/14921-llm-add-api-key-fallback
May 19, 2026
Merged

KevinHuSh merged 2 commits into
infiniflow:mainfrom
Rene0422:fix/14921-llm-add-api-key-fallback

Conversation

@Rene0422

Copy link
Copy Markdown
Contributor

Summary

Closes #14921.

Reconfiguring an existing LLM provider to enable tool call or
vision fails with Your API key is invalid. Fail to access model.
even when the saved API key is correct. The most visible report is
VLLM ("Cannot add vllm model" once --enable-auto-tool-choice /
vision is toggled on), but the bug applies to every provider whose
api_key field stays blank in edit mode.

Root cause

PR #14885 ("Fix: llm add api key overridden") removed the existing-key
lookup in api/apps/llm_app.py::add_llm. The intent was correct —
stop the saved key from clobbering a user-provided new one — but the
removal was unconditional, so the edit path now has no fallback at all:

  1. web/src/pages/user-setting/setting-model/hooks.tsx:230 sets the
    initial api_key form value to '' in edit mode (the real key is
    never returned to the browser).
  2. The user toggles is_tools / vision without retyping the key.
  3. hooks.tsx:183-185 strips the empty api_key from the payload.
  4. add_llm defaults to the placeholder "x"
    (api/apps/llm_app.py:182).
  5. The upstream provider rejects "x" with Your API key is invalid.

Fix

Restore the fallback narrowly, before any factory-specific handler
runs:

  • If req.get("api_key") is None, look up the tenant's existing record
    (using the correctly suffixed llm_name for VLLM /
    OpenAI-API-Compatible / LocalAI / HuggingFace).
  • Decode the saved blob with _decode_api_key_config and write only
    the decoded api_key string
    back into req["api_key"]. Never use
    the raw JSON payload — that was the exact thing PR Fix: llm add api key overridden #14885 was trying
    to avoid.
  • When the user does type a new key, req.get("api_key") is not
    None and the fallback is skipped, so PR Fix: llm add api key overridden #14885's fix is preserved.
Scenario Before this PR After this PR
Plain factory (VLLM, Ollama, …), retype key OK OK
Plain factory, blank key in edit (the bug) Fails with "API key is invalid" Recovers saved key, validates against the real one
OpenRouter / Bedrock, change provider_order only Fails apikey_json([...]) rebuilds the JSON with saved api_key + new field
User clears the form and types a brand-new key OK (key replaced) OK (key replaced — fallback skipped)

Files changed

  • api/apps/llm_app.py — restored fallback in add_llm (no other call sites touched).

Test plan

  • Add a VLLM chat model with a valid api_key, no toggles → save succeeds.
  • Edit the same model, toggle tool call on, leave api_key blank
    → save succeeds, validation runs against the saved key.
  • Edit again, toggle vision on (model_type → image2text),
    leave api_key blank → save succeeds.
  • Edit again and type a new api_key → the new key replaces the
    saved one (is None check skips the fallback). Verify via the DB
    row or by deliberately typing a wrong key and observing the
    validation failure.
  • Repeat the blank-key edit with OpenRouter, changing only
    provider_order → resulting api_key JSON contains the saved
    api_key and the new provider_order.
  • First-time add of a new model name → no existing record, fallback
    no-ops, behaves as before.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 15, 2026
@coderabbitai

coderabbitai Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 65747f0c-cabb-484a-b480-0109f0336bb2

📥 Commits

Reviewing files that changed from the base of the PR and between 828f897 and 7d687cd.

📒 Files selected for processing (1)
  • api/apps/llm_app.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/llm_app.py

📝 Walkthrough

Walkthrough

The add_llm endpoint reorders initialization and now recovers a previously saved tenant API key when the frontend sends llm_name but omits api_key: it looks up the tenant's existing TenantLLM, decodes the stored credential, and repopulates req["api_key"] before downstream provider validation.

Changes

API Key Recovery for LLM edits

Layer / File(s) Summary
Request parsing & early validation
api/apps/llm_app.py
Read llm_name and timeout_seconds earlier and run the "factory allowed" check before attempting API-key recovery.
Saved API-key recovery flow
api/apps/llm_app.py, services/tenant_llm_service.py (usage)
When req.get("api_key") is None and llm_name is present, construct a factory-specific saved name, query the tenant's existing TenantLLM entry, decode the stored api_key via TenantLLMService._decode_api_key_config, and set req["api_key"] to the decoded key.
Downstream auth defaulting
api/apps/llm_app.py
After recovery attempt, set api_key = req.get("api_key", "x") for provider-specific authentication branches.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14885: Modifies api/apps/llm_app.py:add_llm API-key fallback behavior; directly related to undoing/changing tenant-key fallback logic.
  • infiniflow/ragflow#14707: Also adjusts add_llm handling when req["api_key"] is missing (Bedrock JSON credential handling overlaps).

Suggested labels

🐞 bug

Suggested reviewers

  • wangq8
  • Lynn-Inf

Poem

🐰 I dug through saved keys in the night,
Found the secret that made edits right.
A decoded hop from vault to request,
Now models awake and pass the test. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately summarizes the main change: restoring a saved API key fallback mechanism in the add_llm function to fix the bug where editing LLM providers with blank API keys failed.
Description check ✅ Passed The PR description comprehensively covers the problem statement, root cause analysis, detailed fix explanation with a comparison table, affected files, and an extensive test plan matching the template requirements.
Linked Issues check ✅ Passed The PR successfully addresses issue #14921 by implementing the fallback logic that allows editing VLLM and other LLM providers without retyping the API key, directly resolving the reported bug of 'Your API key is invalid' errors.
Out of Scope Changes check ✅ Passed All changes in api/apps/llm_app.py are directly scoped to the add_llm function's API key recovery logic required to fix issue #14921, with no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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/apps/llm_app.py (1)

197-203: ⚡ Quick win

Suffix map duplicates the per-factory branches below; extract a single source of truth.

The mapping in _LLM_NAME_SUFFIX (lines 197–202) restates the same suffix policy that is hand-rolled in the elif factory == "LocalAI"/"HuggingFace"/"OpenAI-API-Compatible"/"VLLM" branches at lines 238–248. Any future change (new factory, renamed suffix) must be made in both places or the fallback silently fails to locate the saved row. Lifting it to a module-level constant and reusing it in both spots removes the drift risk.

♻️ Proposed refactor
+# Factories whose stored TenantLLM.llm_name is suffixed to disambiguate user-named models.
+_LLM_NAME_SUFFIX = {
+    "LocalAI": "___LocalAI",
+    "HuggingFace": "___HuggingFace",
+    "OpenAI-API-Compatible": "___OpenAI-API",
+    "VLLM": "___VLLM",
+}
+
 `@manager.route`("/add_llm", methods=["POST"])  # noqa: F821
 ...
-    if req.get("api_key") is None and llm_name:
-        _LLM_NAME_SUFFIX = {
-            "LocalAI": "___LocalAI",
-            "HuggingFace": "___HuggingFace",
-            "OpenAI-API-Compatible": "___OpenAI-API",
-            "VLLM": "___VLLM",
-        }
-        saved_llm_name = llm_name + _LLM_NAME_SUFFIX.get(factory, "")
+    if req.get("api_key") is None and llm_name:
+        saved_llm_name = llm_name + _LLM_NAME_SUFFIX.get(factory, "")
...
-    elif factory == "LocalAI":
-        llm_name += "___LocalAI"
-
-    elif factory == "HuggingFace":
-        llm_name += "___HuggingFace"
-
-    elif factory == "OpenAI-API-Compatible":
-        llm_name += "___OpenAI-API"
-
-    elif factory == "VLLM":
-        llm_name += "___VLLM"
+    elif factory in _LLM_NAME_SUFFIX:
+        llm_name += _LLM_NAME_SUFFIX[factory]
🤖 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/llm_app.py` around lines 197 - 203, The suffix map is duplicated:
extract _LLM_NAME_SUFFIX into a single module-level constant and use that
constant wherever suffixes are determined (replace the inline map and the
per-factory branches that currently hand-roll suffixes); update the
saved_llm_name computation (using llm_name + SUFFIX_MAP.get(factory, "")) and
refactor the factory-specific branches (the blocks checking factory ==
"LocalAI"/"HuggingFace"/"OpenAI-API-Compatible"/"VLLM") to reference the same
SUFFIX_MAP constant so there is a single source of truth for factory→suffix
mapping (keep existing keys "LocalAI", "HuggingFace", "OpenAI-API-Compatible",
"VLLM").
🤖 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/llm_app.py`:
- Around line 196-214: Add structured logging to the API-key recovery flow
inside the block that checks req.get("api_key") is None and llm_name: emit a
debug/info log when you attempt recovery (include llm_name and factory), log
whether TenantLLMService.query returned any matching existing_llms (e.g., count
or existence) and log the result of TenantLLMService._decode_api_key_config as
"decoded key present" vs "no decoded key" without ever logging the actual
decoded value; update the branch that assigns req["api_key"] to also log that
the request was mutated (include non-sensitive context like saved_llm_name and
tenant id/current_user.id) and ensure logs use the existing project
logger/structured fields rather than printing.

---

Nitpick comments:
In `@api/apps/llm_app.py`:
- Around line 197-203: The suffix map is duplicated: extract _LLM_NAME_SUFFIX
into a single module-level constant and use that constant wherever suffixes are
determined (replace the inline map and the per-factory branches that currently
hand-roll suffixes); update the saved_llm_name computation (using llm_name +
SUFFIX_MAP.get(factory, "")) and refactor the factory-specific branches (the
blocks checking factory ==
"LocalAI"/"HuggingFace"/"OpenAI-API-Compatible"/"VLLM") to reference the same
SUFFIX_MAP constant so there is a single source of truth for factory→suffix
mapping (keep existing keys "LocalAI", "HuggingFace", "OpenAI-API-Compatible",
"VLLM").
🪄 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: 8f9d8aa8-27a9-4636-a2db-a27f9c4b1522

📥 Commits

Reviewing files that changed from the base of the PR and between 5a5bbee and 828f897.

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

Comment thread api/apps/llm_app.py Resolved
@KevinHuSh KevinHuSh added the ci Continue Integration label May 19, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 19, 2026 05:44
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 19, 2026 05:44
@codecov

codecov Bot commented May 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (5a5bbee) to head (7d687cd).
⚠️ Report is 47 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14941      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@KevinHuSh
KevinHuSh merged commit ce3402c into infiniflow:main May 19, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Can not add vllm model

2 participants