Skip to content

Fix: Bedrock api_key overridden by existing-key fallback in add_llm - #14707

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
Eurelis:fix/bedrock-add-llm-api-key-override
May 9, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
Eurelis:fix/bedrock-add-llm-api-key-override

Conversation

@vincentlambert

Copy link
Copy Markdown
Contributor

Summary

  • Adding a Bedrock model from the frontend fails with Fail to access model(Bedrock/<model>).Expecting value: line 1 column 1 (char 0).
  • The assembled Bedrock JSON credentials are silently replaced by "x" before the connection test, causing json.loads("x") to raise a JSONDecodeError.

What problem does this PR solve?

Commit 050113482 introduced a fallback in add_llm() that reuses the existing DB key when req.get("api_key") is None:

if req.get("api_key") is None:
    api_key = existing_api_key if existing_api_key is not None else "x"

For Bedrock, credentials are sent as separate fields (auth_mode, bedrock_ak, bedrock_sk, bedrock_region, aws_role_arn) — the frontend does not send an api_key field. The function correctly assembles the JSON key:

api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])

But since req.get("api_key") is None, the override immediately replaces api_key with "x" (or a stale DB value). LiteLLMBase then calls json.loads("x") for Bedrock auth → JSONDecodeError.

Type of change

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

Changes

api/apps/llm_app.py

Write the assembled key into req["api_key"] so the None check evaluates to False and the override is skipped — consistent with how Tencent Cloud is already handled.

# Before
api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])

# After
req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
api_key = req["api_key"]

Test plan

  • Configure a Bedrock provider in Model Providers with valid AWS credentials
  • Add a Bedrock chat model — verify no Expecting value error
  • Update the same model — verify the existing key is reused correctly when credentials fields are left empty

🤖 Generated with Claude Code

…in add_llm

Upstream commit 0501134 introduced a fallback that replaces api_key with
the existing DB value when req["api_key"] is None. For Bedrock, credentials
are sent as separate fields (bedrock_ak, bedrock_sk, etc.) so req["api_key"]
is always None — causing the assembled JSON key to be silently replaced by
"x", which then fails json.loads() during the connection test.

Fix: write the assembled key into req["api_key"] so the None check is False.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label May 8, 2026
@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The add_llm function's Bedrock factory branch now assigns the assembled authentication payload JSON to req["api_key"] before extracting api_key, ensuring downstream key-presence checks correctly identify populated credentials for Bedrock.

Changes

Bedrock Authentication Payload Assignment

Layer / File(s) Summary
Bedrock Key Assignment
api/apps/llm_app.py
Auth JSON payload is written to req["api_key"] before api_key extraction, fixing downstream key-presence validation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Poem

🐰 A key that hides in shadows deep,
Now nestles safe in req's keep,
The payload flows to check its state—
Bedrock's auth will validate! ✨

🚥 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 clearly identifies the bug being fixed (Bedrock api_key overridden) and the specific location (existing-key fallback in add_llm), matching the core change in the code.
Description check ✅ Passed The PR description fully adheres to the template with detailed problem explanation, bug fix type selection, specific code changes, and comprehensive test plan included.
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.

@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label May 8, 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

🧹 Nitpick comments (1)
api/apps/llm_app.py (1)

202-207: ⚡ Quick win

Missing logging for the new Bedrock flow.

The Bedrock branch is a new/modified code path but does not emit any log entry, unlike the rest of the function (e.g., line 142 logs rerank pass/fail). A single debug log when the Bedrock JSON key is assembled aids troubleshooting similar auth issues in future.

         req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
         api_key = req["api_key"]
+        logging.debug("Bedrock: assembled api_key from request credentials for llm_name=%s", llm_name)

As per coding guidelines: "Add logging for new flows" for **/*.py files.

🤖 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 202 - 207, Add a debug log in the Bedrock
branch (the block where factory == "Bedrock") immediately after assembling
req["api_key"] / api_key via apikey_json so the new flow is visible in logs; use
the same logger instance used elsewhere in this function and log a concise
message like "Bedrock auth assembled" including only non-secret fields (e.g.,
auth_mode, bedrock_region, aws_role_arn) from the apikey_json result and ensure
bedrock_ak/bedrock_sk are not printed.
🤖 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 202-207: The Bedrock branch sets req["api_key"] to
apikey_json(...) unconditionally, which produces a non-null JSON string even
when all Bedrock fields are empty and thus prevents the existing-key fallback
from running; change the logic in the factory == "Bedrock" branch to inspect the
individual fields (auth_mode, bedrock_ak, bedrock_sk, bedrock_region,
aws_role_arn) and only assign req["api_key"] = apikey_json(...) if at least one
of those fields is non-empty/Truthy, otherwise leave req["api_key"] unset so the
later req.get("api_key") fallback will reuse the stored key. Ensure you
reference the same apikey_json helper and the req["api_key"] slot used by the
fallback logic.

---

Nitpick comments:
In `@api/apps/llm_app.py`:
- Around line 202-207: Add a debug log in the Bedrock branch (the block where
factory == "Bedrock") immediately after assembling req["api_key"] / api_key via
apikey_json so the new flow is visible in logs; use the same logger instance
used elsewhere in this function and log a concise message like "Bedrock auth
assembled" including only non-secret fields (e.g., auth_mode, bedrock_region,
aws_role_arn) from the apikey_json result and ensure bedrock_ak/bedrock_sk are
not printed.
🪄 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: 1be761d6-a172-4c3f-ba46-14264a3d0df7

📥 Commits

Reviewing files that changed from the base of the PR and between 5e96c5c and 9b2b26c.

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

Comment thread api/apps/llm_app.py
Comment on lines 202 to +207
elif factory == "Bedrock":
# For Bedrock, due to its special authentication method
# Assemble bedrock_ak, bedrock_sk, bedrock_region
api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
# Write into req["api_key"] to prevent the "existing key" override logic from replacing it
req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
api_key = req["api_key"]

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 | 🟠 Major | ⚡ Quick win

Empty Bedrock credentials bypass the existing-key fallback, breaking update-without-re-entering-credentials.

When a user updates an existing Bedrock model without supplying new credentials, all the Bedrock-specific fields (auth_mode, bedrock_ak, etc.) are absent or empty strings in req. apikey_json produces '{"auth_mode": "", "bedrock_ak": "", "bedrock_sk": "", "bedrock_region": "", "aws_role_arn": ""}' — a non-None string. Writing this to req["api_key"] before the fallback check at line 253 means req.get("api_key") is None is never True for Bedrock, so the stored key is never reused and empty credentials are persisted to the DB. This contradicts the PR's own test-plan point: "Update the model and verify existing key reuse when credential fields are left empty".

The fix should conditionally write to req["api_key"] only when at least one credential field carries a real value, allowing the existing-key fallback to run when the user supplies nothing new.

🐛 Proposed fix
     elif factory == "Bedrock":
         # For Bedrock, due to its special authentication method
         # Assemble bedrock_ak, bedrock_sk, bedrock_region
-        # Write into req["api_key"] to prevent the "existing key" override logic from replacing it
-        req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
-        api_key = req["api_key"]
+        # Only write into req["api_key"] when real credentials were provided so that
+        # the "existing key" fallback can still run when the user leaves all fields empty.
+        _bedrock_keys = ["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"]
+        if any(req.get(k) for k in _bedrock_keys):
+            req["api_key"] = apikey_json(_bedrock_keys)
+            api_key = req["api_key"]
📝 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
elif factory == "Bedrock":
# For Bedrock, due to its special authentication method
# Assemble bedrock_ak, bedrock_sk, bedrock_region
api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
# Write into req["api_key"] to prevent the "existing key" override logic from replacing it
req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
api_key = req["api_key"]
elif factory == "Bedrock":
# For Bedrock, due to its special authentication method
# Assemble bedrock_ak, bedrock_sk, bedrock_region
# Only write into req["api_key"] when real credentials were provided so that
# the "existing key" fallback can still run when the user leaves all fields empty.
_bedrock_keys = ["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"]
if any(req.get(k) for k in _bedrock_keys):
req["api_key"] = apikey_json(_bedrock_keys)
api_key = req["api_key"]
🤖 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 202 - 207, The Bedrock branch sets
req["api_key"] to apikey_json(...) unconditionally, which produces a non-null
JSON string even when all Bedrock fields are empty and thus prevents the
existing-key fallback from running; change the logic in the factory == "Bedrock"
branch to inspect the individual fields (auth_mode, bedrock_ak, bedrock_sk,
bedrock_region, aws_role_arn) and only assign req["api_key"] = apikey_json(...)
if at least one of those fields is non-empty/Truthy, otherwise leave
req["api_key"] unset so the later req.get("api_key") fallback will reuse the
stored key. Ensure you reference the same apikey_json helper and the
req["api_key"] slot used by the fallback logic.

@vincentlambert

Copy link
Copy Markdown
Contributor Author

Hi @yingfeng — this PR fixes a regression introduced by your commit 050113482 (Fix: support tool call config #14616).

That commit added a fallback in add_llm() to reuse an existing DB key when req.get("api_key") is None. This is correct for most providers, but breaks Bedrock: the frontend sends credentials as separate fields (bedrock_ak, bedrock_sk, etc.) and never sets api_key — so the newly assembled JSON key is silently replaced by "x", which then causes json.loads("x") → JSONDecodeError during the connection test.

The fix is a one-liner, consistent with how Tencent Cloud is already handled in the same function.

@yingfeng
yingfeng requested a review from wangq8 May 9, 2026 01:28
@yingfeng yingfeng added the ci Continue Integration label May 9, 2026
@yingfeng
yingfeng marked this pull request as draft May 9, 2026 01:29
@yingfeng
yingfeng marked this pull request as ready for review May 9, 2026 01:29
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 9, 2026
@wangq8

wangq8 commented May 9, 2026

Copy link
Copy Markdown
Collaborator

@Lynn-Inf please consider handle this logic in the new refined code.

@wangq8
wangq8 requested a review from Lynn-Inf May 9, 2026 01:35
@codecov

codecov Bot commented May 9, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (5e96c5c) to head (3459a7d).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14707      +/-   ##
==========================================
- 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.

@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

@wangq8
wangq8 merged commit 870bc59 into infiniflow:main May 9, 2026
2 checks passed
@vincentlambert
vincentlambert deleted the fix/bedrock-add-llm-api-key-override branch June 4, 2026 16:03
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…nfiniflow#14707)

## Summary

- Adding a Bedrock model from the frontend fails with `Fail to access
model(Bedrock/<model>).Expecting value: line 1 column 1 (char 0)`.
- The assembled Bedrock JSON credentials are silently replaced by `"x"`
before the connection test, causing `json.loads("x")` to raise a
`JSONDecodeError`.

## What problem does this PR solve?

Commit `050113482` introduced a fallback in `add_llm()` that reuses the
existing DB key when `req.get("api_key") is None`:

```python
if req.get("api_key") is None:
    api_key = existing_api_key if existing_api_key is not None else "x"
```

For Bedrock, credentials are sent as separate fields (`auth_mode`,
`bedrock_ak`, `bedrock_sk`, `bedrock_region`, `aws_role_arn`) — the
frontend does not send an `api_key` field. The function correctly
assembles the JSON key:

```python
api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
```

But since `req.get("api_key")` is `None`, the override immediately
replaces `api_key` with `"x"` (or a stale DB value). `LiteLLMBase` then
calls `json.loads("x")` for Bedrock auth → `JSONDecodeError`.

## Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

## Changes

**`api/apps/llm_app.py`**

Write the assembled key into `req["api_key"]` so the `None` check
evaluates to `False` and the override is skipped — consistent with how
`Tencent Cloud` is already handled.

```python
# Before
api_key = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])

# After
req["api_key"] = apikey_json(["auth_mode", "bedrock_ak", "bedrock_sk", "bedrock_region", "aws_role_arn"])
api_key = req["api_key"]
```

## Test plan

- [ ] Configure a Bedrock provider in Model Providers with valid AWS
credentials
- [ ] Add a Bedrock chat model — verify no `Expecting value` error
- [ ] Update the same model — verify the existing key is reused
correctly when credentials fields are left empty

🤖 Generated with [Claude Code](https://claude.ai/claude-code)

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
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 lgtm This PR has been approved by a maintainer size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants