Skip to content

Fix OpenRouter key JSONDecodeError - #15776

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-openrouter-key
Jun 8, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
wangq8:bugfix/fix-openrouter-key

Conversation

@wangq8

@wangq8 wangq8 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Fix OpenRouter key JSONDecodeError

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds error tolerance to OpenRouter configuration parsing in two LLM model classes. JSON parsing of the OpenRouter key now gracefully falls back to treating the input as a raw API key string if JSON decoding fails, instead of raising an exception.

Changes

OpenRouter Configuration Parsing

Layer / File(s) Summary
OpenRouter key parsing error tolerance
rag/llm/chat_model.py, rag/llm/cv_model.py
LiteLLMBase.__init__ and OpenRouterCV.__init__ wrap JSON parsing of the OpenRouter configuration key in try/except JSONDecodeError blocks. On parse failure, the original key is used as the API key and provider_order is set to an empty string, eliminating JSON decode exceptions for non-JSON input.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 JSON parsing now bows gracefully,
When keys arrive plain instead of structured—
No crashes here, just fallback care,
Two classes learn to share this air,
Error-proof and debonair! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is minimal and lacks required template sections, only repeating the title without problem statement or change type classification. Add a 'What problem does this PR solve?' section with context and select a 'Type of change' checkbox from the provided template.
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 clearly describes the main change: fixing a JSONDecodeError issue with OpenRouter key parsing.
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.

@wangq8 wangq8 added the ci Continue Integration label Jun 8, 2026
@wangq8
wangq8 marked this pull request as ready for review June 8, 2026 09:51
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jun 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.

🧹 Nitpick comments (4)
rag/llm/cv_model.py (2)

638-643: ⚡ Quick win

Add logging for the fallback path.

The fallback to treating the key as a raw API key is a new flow that should be logged. As per coding guidelines, add logging for new flows.

📝 Proposed fix
         try:
             api_key = json.loads(key).get("api_key", "")
             provider_order = json.loads(key).get("provider_order", "")
         except JSONDecodeError:
+            logging.info("[OpenRouterCV] Key is not JSON, treating as raw API key")
             api_key = key
             provider_order = ""
🤖 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/llm/cv_model.py` around lines 638 - 643, The fallback path that treats
'key' as a raw API key isn't logged; update the except JSONDecodeError block
(the try that sets api_key = json.loads(key).get("api_key", "") and
provider_order = json.loads(key).get("provider_order", "")) to emit a log entry
when the fallback runs, e.g., use the module logger (logger or
logging.getLogger(__name__)) to log a warning/info that JSON decoding failed and
that 'key' is being used as a raw API key, including the exception message for
context; keep the existing assignments (api_key = key, provider_order = "")
unchanged.

Source: Coding guidelines


638-643: ⚡ Quick win

Parse JSON once to avoid redundant decoding.

The json.loads(key) call is duplicated on lines 639 and 640. Parse the JSON once, store the result, then extract both fields from the parsed object.

♻️ Proposed refactor
         try:
-            api_key = json.loads(key).get("api_key", "")
-            provider_order = json.loads(key).get("provider_order", "")
+            parsed_key = json.loads(key)
+            api_key = parsed_key.get("api_key", "")
+            provider_order = parsed_key.get("provider_order", "")
         except JSONDecodeError:
             api_key = key
             provider_order = ""
🤖 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/llm/cv_model.py` around lines 638 - 643, The code calls json.loads(key)
twice when extracting api_key and provider_order; instead, parse once into a
local variable (e.g., parsed = json.loads(key)) inside the try block and then
read parsed.get("api_key", "") and parsed.get("provider_order", ""); keep the
except JSONDecodeError branch to fall back to treating key as a plain api_key
and setting provider_order to "" (same behavior), and ensure variable names
api_key and provider_order remain unchanged.
rag/llm/chat_model.py (2)

1374-1379: ⚡ Quick win

Add logging for the fallback path.

The fallback to treating the key as a raw API key is a new flow that should be logged. As per coding guidelines, add logging for new flows.

📝 Proposed fix
         if self.provider == SupportedLiteLLMProvider.OpenRouter:
             try:
                 self.api_key = json.loads(key).get("api_key", "")
                 self.provider_order = json.loads(key).get("provider_order", "")
             except JSONDecodeError:
+                logging.info(f"[{self.provider}] Key is not JSON, treating as raw API key")
                 self.api_key = key
                 self.provider_order = ""
🤖 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/llm/chat_model.py` around lines 1374 - 1379, The exception handler that
falls back to treating key as a raw API key (catching JSONDecodeError) needs a
log entry so the new flow is observable; inside the except JSONDecodeError block
(where self.api_key = key and self.provider_order = "") add a concise debug/info
log via the module/class logger (e.g., logger or self.logger if available)
indicating JSON parsing failed and you're falling back to raw key along with
minimal context (do not log full secret — mask/summarize if necessary) and
include the exception message to aid debugging.

Source: Coding guidelines


1374-1379: ⚡ Quick win

Parse JSON once to avoid redundant decoding.

The json.loads(key) call is duplicated on lines 1375 and 1376. Parse the JSON once, store the result, then extract both fields from the parsed object.

♻️ Proposed refactor
         if self.provider == SupportedLiteLLMProvider.OpenRouter:
             try:
-                self.api_key = json.loads(key).get("api_key", "")
-                self.provider_order = json.loads(key).get("provider_order", "")
+                parsed_key = json.loads(key)
+                self.api_key = parsed_key.get("api_key", "")
+                self.provider_order = parsed_key.get("provider_order", "")
             except JSONDecodeError:
                 self.api_key = key
                 self.provider_order = ""
🤖 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/llm/chat_model.py` around lines 1374 - 1379, Parse the JSON only once and
reuse the result to populate self.api_key and self.provider_order: inside the
try block (where json.loads(key) and JSONDecodeError are referenced) call
json.loads(key) a single time into a local variable (e.g., parsed =
json.loads(key)) and then set self.api_key = parsed.get("api_key", "") and
self.provider_order = parsed.get("provider_order", ""); keep the except
JSONDecodeError branch to fallback to self.api_key = key and self.provider_order
= "".
🤖 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 `@rag/llm/chat_model.py`:
- Around line 1374-1379: The exception handler that falls back to treating key
as a raw API key (catching JSONDecodeError) needs a log entry so the new flow is
observable; inside the except JSONDecodeError block (where self.api_key = key
and self.provider_order = "") add a concise debug/info log via the module/class
logger (e.g., logger or self.logger if available) indicating JSON parsing failed
and you're falling back to raw key along with minimal context (do not log full
secret — mask/summarize if necessary) and include the exception message to aid
debugging.
- Around line 1374-1379: Parse the JSON only once and reuse the result to
populate self.api_key and self.provider_order: inside the try block (where
json.loads(key) and JSONDecodeError are referenced) call json.loads(key) a
single time into a local variable (e.g., parsed = json.loads(key)) and then set
self.api_key = parsed.get("api_key", "") and self.provider_order =
parsed.get("provider_order", ""); keep the except JSONDecodeError branch to
fallback to self.api_key = key and self.provider_order = "".

In `@rag/llm/cv_model.py`:
- Around line 638-643: The fallback path that treats 'key' as a raw API key
isn't logged; update the except JSONDecodeError block (the try that sets api_key
= json.loads(key).get("api_key", "") and provider_order =
json.loads(key).get("provider_order", "")) to emit a log entry when the fallback
runs, e.g., use the module logger (logger or logging.getLogger(__name__)) to log
a warning/info that JSON decoding failed and that 'key' is being used as a raw
API key, including the exception message for context; keep the existing
assignments (api_key = key, provider_order = "") unchanged.
- Around line 638-643: The code calls json.loads(key) twice when extracting
api_key and provider_order; instead, parse once into a local variable (e.g.,
parsed = json.loads(key)) inside the try block and then read
parsed.get("api_key", "") and parsed.get("provider_order", ""); keep the except
JSONDecodeError branch to fall back to treating key as a plain api_key and
setting provider_order to "" (same behavior), and ensure variable names api_key
and provider_order remain unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f4404c4a-ff45-4e4f-b390-7ca5e84e9bfc

📥 Commits

Reviewing files that changed from the base of the PR and between 86b320e and 40274f7.

📒 Files selected for processing (2)
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py

@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (e81bca7) to head (40274f7).
⚠️ Report is 16 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15776   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ 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 merged commit 8e4fba6 into infiniflow:main Jun 8, 2026
1 check passed
Harsh23Kashyap added a commit to Harsh23Kashyap/ragflow that referenced this pull request Aug 20, 2026
)

The OpenRouter provider in rag/llm has three call sites that do an
unguarded `json.loads(key).get("api_key", "")` inside a
`try: ... except JSONDecodeError:` block (chat and CV) or with an
`isinstance(payload, dict)` fallback (embedding):

- LiteLLMBase.__init__ (chat, OpenRouter branch) -- chat_model.py:1627
- OpenRouterCV.__init__     (vision)              -- cv_model.py:698
- OpenRouterEmbed.__init__  (embedding)           -- embedding_model.py:1338

The `except JSONDecodeError` only catches the *parse* failure (added
by PR infiniflow#15776 / commit 8e4fba6). A user pasting a JSON string that is
NOT an object -- e.g. `"[1,2,3]"`, `"42"", `'"hello"'`,
`"true"", `"null"` -- parses fine and then crashes on the
`.get(...)` call with `AttributeError: 'list' object has no
attribute 'get'` (or `'int'`, `'str'`, `'NoneType'`, `'bool'`)
from inside rag/llm internals -- no indication of what the user did
wrong. The embedding site does not crash (it has the
`isinstance(payload, dict)` check) but silently uses the raw JSON
string as api_key, which then fails at the OpenAI client with a
less-actionable 401 Unauthorized.

Fix: add `_resolve_openrouter_credentials` to rag/llm/key_utils, then
wire the three call sites through it. The helper:

- Accepts a plain (non-JSON) string and returns
  `{"api_key": key, "provider_order": ""}` -- matching the
  pre-fix `except JSONDecodeError` fallback semantics.
- Accepts a dict (returned verbatim) or a JSON-string-encoded dict
  (parsed and returned) with both fields extracted.
- On a JSON top-level type that is not a dict (list, string, number,
  bool, null), raises a clear `ModelException(retryable=False)` naming
  the required object shape and pointing at
  `conf/models/openrouter.json`. Operators can self-diagnose without
  opening an issue.

Behavior unchanged for the existing happy paths:

- Plain key      -> `api_key = key, provider_order = ""` (preserves fallback)
- JSON dict      -> `api_key = parsed["api_key"]`, `provider_order = parsed["provider_order"]`
- Missing fields -> defaults to `""` (unchanged from pre-fix)

No public API change. No data-model change. No migration.

Fixes infiniflow#17458.
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant