Skip to content

Fix: llm add api key overridden - #14885

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b047
May 13, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b047

Conversation

@buua436

@buua436 buua436 commented May 13, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

llm add api key overridden

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR removes the API key fallback logic in the add_llm backend route and updates the model identifier field label across all 14 language locales from "EndpointID" to "Model ID" for consistent user-facing terminology.

Changes

API Key Fallback Removal

Layer / File(s) Summary
Remove existing TenantLLM API key fallback
api/apps/llm_app.py
The add_llm route's VolcEngine section clarifies how ark_api_key fields are assembled into api_key, and the fallback behavior that queried previously stored TenantLLM api_key values when none was provided in the request is removed.

Model ID Label Harmonization

Layer / File(s) Summary
Update model identifier labels across locales
web/src/locales/ar.ts, web/src/locales/bg.ts, web/src/locales/de.ts, web/src/locales/en.ts, web/src/locales/es.ts, web/src/locales/fr.ts, web/src/locales/id.ts, web/src/locales/ja.ts, web/src/locales/pt-br.ts, web/src/locales/ru.ts, web/src/locales/tr.ts, web/src/locales/vi.ts, web/src/locales/zh-traditional.ts, web/src/locales/zh.ts
The addEndpointID and endpointIDMessage UI strings are updated to use "Model ID" terminology in all supported languages, replacing the previous "EndpointID"-based wording.

Possibly Related PRs

  • infiniflow/ragflow#14707: Both PRs modify api/apps/llm_app.py's add_llm logic around when req.get("api_key") is unset—this PR removes the existing stored TenantLLM api_key fallback, while the related PR fixes Bedrock by writing assembled credentials into req["api_key"] to avoid that fallback.

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested Labels

🐞 bug, size:XS

Suggested Reviewers

  • wangq8
  • Lynn-Inf

Poem

🐰 Endpoints renamed with care so bright,
From tangled "IDs" to "Model" light,
The API's fallback fades away,
Fresh paths for credentials—no yesterday.
Fourteen tongues now speak as one! 🌍

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete. While it includes the 'What problem' section and correct 'Type of change' checkbox, the problem statement is merely a restatement of the title with no substantive context or explanation. Expand the 'What problem does this PR solve?' section with detailed context about the bug, expected vs actual behavior, and impact. Add details about the changes made to fix the issue.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix: llm add api key overridden' accurately describes the main change in the PR—fixing a bug where API keys were being overridden when adding LLMs.
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.

✏️ 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.

@buua436 buua436 added the ci Continue Integration label May 13, 2026
@buua436
buua436 marked this pull request as ready for review May 13, 2026 06:31
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 13, 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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/apps/llm_app.py (1)

182-182: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Update flow silently overwrites stored API keys on partial edits.

Frontend intentionally omits api_key from the request payload when unchanged (see web/src/pages/user-setting/setting-model/hooks.tsx:182-185). However, backend line 182 defaults the missing key to "x", which then gets persisted via the upsert at lines 377-379. For factories without special key assembly (OpenAI, Anthropic, DeepSeek, Moonshot, etc.), any update request that omits api_key will replace the stored credential with "x".

Confirm the frontend always includes api_key on edit (even if unchanged), or restore guarded preservation logic to avoid silently corrupting stored credentials when users submit partial updates.

🤖 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` at line 182, The code is overwriting stored API keys
because api_key = req.get("api_key", "x") uses `"x"` as a default and the upsert
later persists that placeholder; change the logic to preserve existing
credentials when the request omits the key: read api_key from the request
without a magic default (e.g., api_key = req.get("api_key")), and if api_key is
None or equals the sentinel `"x"`, load the current stored key from the
model/credentials record (the same record used in the subsequent upsert) and use
that value for the upsert instead of `"x"`; ensure this preserved value is
passed into the upsert call so partial updates don't clobber stored API keys.
🧹 Nitpick comments (1)
api/apps/llm_app.py (1)

193-196: 💤 Low value

Clarify the VolcEngine comment — code still assembles endpoint_id, not model_id.

The new wording "Assemble ark_api_key model_id into api_key; keep endpoint_id in backend payload for compatibility" is hard to parse: the JSON actually built at line 196 contains ark_api_key and endpoint_id (not model_id). If the intent is to note that the UI now labels the field "Model ID" while the backend payload key stays endpoint_id for backward compatibility, please reword to make that explicit.

✏️ Suggested rewording
     if factory == "VolcEngine":
-        # For VolcEngine, due to its special authentication method
-        # Assemble ark_api_key model_id into api_key; keep endpoint_id in backend payload for compatibility
+        # For VolcEngine, due to its special authentication method.
+        # The UI now labels this field "Model ID", but the backend payload key
+        # remains `endpoint_id` for backward compatibility.
         api_key = apikey_json(["ark_api_key", "endpoint_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/llm_app.py` around lines 193 - 196, The comment for the VolcEngine
branch is misleading: when factory == "VolcEngine" the apikey_json call builds a
JSON with keys "ark_api_key" and "endpoint_id" (not "model_id"); update the
comment above the api_key = apikey_json(["ark_api_key", "endpoint_id"]) line to
explicitly state that the UI may label the field "Model ID" but the backend
keeps the key named "endpoint_id" for backward compatibility and that
ark_api_key is merged into api_key for VolcEngine's auth; reference the factory
variable, the apikey_json call, and the api_key variable so reviewers can find
and verify the change.
🤖 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/locales/en.ts`:
- Line 1489: The message string endpointIDMessage is awkwardly redundant; update
its value to a concise, sentence-case prompt such as "Please input your model
ID" (capitalize only the first word) by editing the endpointIDMessage entry in
the locales object to replace "Please input your Model ID of the model" with the
simplified sentence-case text.

---

Outside diff comments:
In `@api/apps/llm_app.py`:
- Line 182: The code is overwriting stored API keys because api_key =
req.get("api_key", "x") uses `"x"` as a default and the upsert later persists
that placeholder; change the logic to preserve existing credentials when the
request omits the key: read api_key from the request without a magic default
(e.g., api_key = req.get("api_key")), and if api_key is None or equals the
sentinel `"x"`, load the current stored key from the model/credentials record
(the same record used in the subsequent upsert) and use that value for the
upsert instead of `"x"`; ensure this preserved value is passed into the upsert
call so partial updates don't clobber stored API keys.

---

Nitpick comments:
In `@api/apps/llm_app.py`:
- Around line 193-196: The comment for the VolcEngine branch is misleading: when
factory == "VolcEngine" the apikey_json call builds a JSON with keys
"ark_api_key" and "endpoint_id" (not "model_id"); update the comment above the
api_key = apikey_json(["ark_api_key", "endpoint_id"]) line to explicitly state
that the UI may label the field "Model ID" but the backend keeps the key named
"endpoint_id" for backward compatibility and that ark_api_key is merged into
api_key for VolcEngine's auth; reference the factory variable, the apikey_json
call, and the api_key variable so reviewers can find and verify the change.
🪄 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: be92ab10-d741-4c3a-b73c-471d2f31ce45

📥 Commits

Reviewing files that changed from the base of the PR and between d63d3bb and 829fba3.

📒 Files selected for processing (15)
  • api/apps/llm_app.py
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/es.ts
  • web/src/locales/fr.ts
  • web/src/locales/id.ts
  • web/src/locales/ja.ts
  • web/src/locales/pt-br.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/vi.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts

Comment thread web/src/locales/en.ts
addEndpointID: 'EndpointID of the model',
endpointIDMessage: 'Please input your EndpointID of the model',
addEndpointID: 'Model ID',
endpointIDMessage: 'Please input your Model ID of the model',

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Simplify the prompt text to avoid redundancy.

Please input your Model ID of the model is awkward and repetitive. Use a concise message (for example: Please input your model ID).

✏️ Suggested fix
-      endpointIDMessage: 'Please input your Model ID of the model',
+      endpointIDMessage: 'Please input your model ID',
As per coding guidelines, "For translation tasks in `src/locales/en.ts`, use Sentence case style: first word capitalized, rest lowercase."
📝 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
endpointIDMessage: 'Please input your Model ID of the model',
endpointIDMessage: 'Please input your model 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 `@web/src/locales/en.ts` at line 1489, The message string endpointIDMessage is
awkwardly redundant; update its value to a concise, sentence-case prompt such as
"Please input your model ID" (capitalize only the first word) by editing the
endpointIDMessage entry in the locales object to replace "Please input your
Model ID of the model" with the simplified sentence-case text.

@codecov

codecov Bot commented May 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (bf90c89) to head (a154b43).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14885   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

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

@wangq8
wangq8 merged commit 8cb2bf0 into infiniflow:main May 13, 2026
1 check passed
KevinHuSh pushed a commit that referenced this pull request May 19, 2026
## 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 #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 #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

- [x] 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):
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

llm add api key overridden

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
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.

2 participants