Repository navigation
Fix: llm add api key overridden - #14885
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesAPI Key Fallback Removal
Model ID Label Harmonization
Possibly Related PRs
Estimated Code Review Effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested Labels
Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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 liftUpdate flow silently overwrites stored API keys on partial edits.
Frontend intentionally omits
api_keyfrom the request payload when unchanged (seeweb/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 omitsapi_keywill replace the stored credential with"x".Confirm the frontend always includes
api_keyon 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 valueClarify the VolcEngine comment — code still assembles
endpoint_id, notmodel_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_keyandendpoint_id(notmodel_id). If the intent is to note that the UI now labels the field "Model ID" while the backend payload key staysendpoint_idfor 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
📒 Files selected for processing (15)
api/apps/llm_app.pyweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/es.tsweb/src/locales/fr.tsweb/src/locales/id.tsweb/src/locales/ja.tsweb/src/locales/pt-br.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/vi.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.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', |
There was a problem hiding this comment.
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',📝 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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
## 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):
### What problem does this PR solve? llm add api key overridden ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
What problem does this PR solve?
llm add api key overridden
Type of change