Repository navigation
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
💤 Files with no reviewable changes (1)
📝 WalkthroughWalkthroughReplaces unconditional JSON parsing of Azure OpenAI provider keys with guarded parsing that accepts JSON objects or raw API key strings, logging only key length and defaulting api_version to "2024-02-01" when parsing fails. ChangesAzure OpenAI Provider Key Initialization
Estimated code review effort🎯 2 (Simple) | ⏱️ ~5 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 (1)
rag/llm/chat_model.py (1)
1381-1390: ⚡ Quick winDefensive parsing logic is correct; add a log on the JSON fallback path.
The branch handles all five input shapes safely (raw key, JSON blob, bare dict, empty string, malformed JSON), and both arms set
self.api_version, which_construct_completion_args(Lines 1968-1977) requires for Azure.The only gap: the
exceptswallowsJSONDecodeError/TypeErrorsilently. Since this is exactly the verify/auth troubleshooting path the PR targets, a debug log here would make future misconfig diagnosis easier.📝 Proposed logging on fallback
try: key_obj = json.loads(key) if isinstance(key, str) else key - except (json.JSONDecodeError, TypeError): + except (json.JSONDecodeError, TypeError): + logging.debug("[Azure-OpenAI] key is not a JSON blob; treating it as a raw api_key string.") key_obj = NoneAs per coding guidelines, "Add logging for new flows".
🤖 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 1381 - 1390, The except branch swallows JSONDecodeError/TypeError silently; add a debug log there so malformed/JSON fallback cases are visible during auth troubleshooting: inside the except block that sets key_obj = None, log the original key value and the caught exception (or at least note fallback to raw key) using the module/class logger (or logging.getLogger(__name__) if no logger on self), then continue to set self.api_key and self.api_version as currently done; reference symbols: key_obj, key, self.api_key, self.api_version and _construct_completion_args.
🤖 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 1381-1390: The except branch swallows JSONDecodeError/TypeError
silently; add a debug log there so malformed/JSON fallback cases are visible
during auth troubleshooting: inside the except block that sets key_obj = None,
log the original key value and the caught exception (or at least note fallback
to raw key) using the module/class logger (or logging.getLogger(__name__) if no
logger on self), then continue to set self.api_key and self.api_version as
currently done; reference symbols: key_obj, key, self.api_key, self.api_version
and _construct_completion_args.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b380bd86-71b6-4e76-a9e3-4c768b96eb8d
📒 Files selected for processing (1)
rag/llm/chat_model.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15604 +/- ##
=======================================
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:
|
|
Can someone merge this PR please? Thanks in advance. |
|
dup of this PR: #15877 |
#15877) Fixes #15587 ## Problem `AzureEmbed.__init__` in `rag/llm/embedding_model.py` and `AzureGptV4.__init__` in `rag/llm/cv_model.py` both call `json.loads(key)` unconditionally: ```python api_key = json.loads(key).get("api_key", "") api_version = json.loads(key).get("api_version", "2024-02-01") ``` When a user stores a plain API key string (not a JSON object) in the model configuration — which is a valid and common way to configure Azure OpenAI — `json.loads` raises `JSONDecodeError`. This makes the model fail to initialize and causes document parsing/embedding to return a 500 error. ## Fix Wrap `json.loads` in `try/except (json.JSONDecodeError, TypeError)` and fall back to using the raw string as the `api_key` with the default `api_version`. This is the same pattern already applied to the Azure chat model in PR #15604. ## Files changed - `rag/llm/embedding_model.py` — `AzureEmbed.__init__` - `rag/llm/cv_model.py` — `AzureGptV4.__init__` Fixes #15857 --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Wang Qi <[email protected]>
Summary
Fixes #15587. Adding an Azure-OpenAI provider from the UI crashed
at verify time even with a valid API key, because the Azure
constructor assumed
keywas always a JSON blob — but theverify-api-key flow hands it the raw user-typed string.
Root cause
POST /api/v1/providers/Azure-OpenAI/instances→
provider_api_service.create_provider_instance→
verify_api_key(...)atapi/apps/services/provider_api_service.py:376:api_keyhere is the raw user-typed string extracted fromthe request body at
api/apps/restful_apis/provider_api.py:335. It is NOT the JSONblob (
{"api_key": "...", "api_version": "..."}) that theruntime path packs into the
model_instancerow after save.The Azure branch at
rag/llm/chat_model.py:1372-1374did:— so
json.loads("sk-abc123")consumed the first 4 chars as aJSON string literal and choked on the rest with
Extra data: line 1 column 5 (char 4)— exactly the reporter'straceback.
The
char 4is the giveaway: it's where the parser had finishedthe leading string and found unconsumed characters.
The runtime path (after the row is saved) actually does pass JSON,
so the old code worked there. The verify-during-create path was
always broken; it just happened to surface now.
Fix
Mirror the defensive shape the MiniMax branch four lines below
already uses:
So:
api_key+api_version(runtime path, unchanged behaviour)api_key, default version(verify path, previously crashed)
api_key, defaultversion (defensive)
Validation done in this sandbox
Drove the new branch logic in-process against five input
shapes the route exercises:
"sk-abc123"(the repro)api_key="sk-abc123", default versionjson.dumps)All five pass under the new branch. Three of them would have
raised under the old branch.
What's intentionally not in this PR
The neighbouring OpenRouter branch at
rag/llm/chat_model.py:1370-1371has the samejson.loads(key).get(...)anti-pattern. The reporter only hit itwith Azure, and OpenRouter's verify path may pack
provider_orderdifferently from the runtime save shape. Fixingit blindly here risks a different behaviour change. Filed as a
follow-up so the next "add OpenRouter provider" report doesn't
have to rediscover this code.
Test plan
the server, then
POST /api/v1/providers/Azure-OpenAI/instanceswith
{"instance_name": "...", "api_key": "<raw-azure-key>", "base_url": "https://<...>.openai.azure.com/"}. Server logshould show
JSONDecodeError: Extra data: line 1 column 5 (char 4)fromchat_model.py.verify_api_keycleanly. The "Verify" button in theAdd-Azure-OpenAI modal should turn green for a valid key
and report
Fail to access ...for an invalid key —no traceback either way.
instance saved before this PR (i.e. the row contains a JSON
blob in the api_key column) should still verify and chat
normally — the dict-in branch is the same as before.
api_version: add an Azure provider withapi_version=2024-08-01-preview(or whatever the FEpacks). It should be honoured rather than overwritten by
the default.
uv run pytest— the change is localised to one branch inone constructor; no existing test should change behaviour.
Type of change