Repository navigation
Fix OpenRouter key JSONDecodeError - #15776
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesOpenRouter Configuration Parsing
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes 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.
🧹 Nitpick comments (4)
rag/llm/cv_model.py (2)
638-643: ⚡ Quick winAdd 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 winParse 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 winAdd 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 winParse 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
📒 Files selected for processing (2)
rag/llm/chat_model.pyrag/llm/cv_model.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
) 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.
Fix OpenRouter key JSONDecodeError