Repository navigation
fix: tolerate raw api_key string in AzureEmbed and AzureGptV4 __init__ - #15877
Conversation
AzureEmbed (embedding_model.py) and AzureGptV4 (cv_model.py) both call json.loads(key) unconditionally. When the user stores a plain API key string instead of a JSON object, this raises JSONDecodeError and the model fails to initialise, breaking document parsing with a 500 error. Wrap json.loads in try/except (same pattern as PR infiniflow#15604 for the chat model) so that a raw string is used as-is with the default api_version. Fixes infiniflow#15857 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
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 skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a helper to safely parse Azure credential payloads and updates AzureGptV4 and AzureEmbed initializers to use it, falling back to the raw key as api_key and defaulting api_version to "2024-02-01" when parsing fails. ChangesAzure Credential Parsing Robustness
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ 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: 2
🧹 Nitpick comments (2)
rag/llm/embedding_model.py (1)
247-249: ⚡ Quick winLog when raw-key fallback is activated.
This introduces a new runtime branch and should emit a concise log for observability/troubleshooting when malformed credential payloads are received.
As 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/embedding_model.py` around lines 247 - 249, Add a concise log inside the except (json.JSONDecodeError, TypeError) fallback branch so we record that the raw-key fallback was used and include minimal context for troubleshooting (e.g., anonymized/partial value of key and that api_version was set to "2024-02-01"); update the except block handling in embedding_model.py (the branch setting api_key = key and api_version = "2024-02-01") to call the module/class logger (or a provided logger variable) with a short message like "Malformed credential payload; using raw API key fallback" plus non-sensitive context, ensuring no full secrets are logged.Source: Coding guidelines
rag/llm/cv_model.py (1)
309-311: ⚡ Quick winAdd fallback-path logging for this new credential flow.
The new raw-key fallback path is silent. Add one info/warning log when fallback is used so credential-shape issues are diagnosable in production.
As 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/cv_model.py` around lines 309 - 311, The except block that falls back to treating `key` as a raw API key is silent; change the handler for json.JSONDecodeError/TypeError to capture the exception (e.g., `except (json.JSONDecodeError, TypeError) as e:`) and emit a single info/warning log that the raw-key fallback was used, include the exception message and a masked form of `key` for diagnostics, then set `api_key = key` and `api_version = "2024-02-01"`; use the module/class logger used elsewhere in this file (e.g., `logger` or `self.logger`) to perform the log call.Source: Coding guidelines
🤖 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 `@rag/llm/cv_model.py`:
- Around line 305-311: The parsed result from json.loads(key) may be a non-dict
valid JSON (string, number, list, null) so change the block around
json.loads(key) to validate that key_obj is a dict before calling .get; if
isinstance(key_obj, dict) extract api_key = key_obj.get("api_key", "") and
api_version = key_obj.get("api_version", "2024-02-01"), otherwise treat the
parsed value as a raw key (e.g., api_key = key if parsed is not a dict or if
it's None) and set api_version = "2024-02-01"; keep the existing except
(json.JSONDecodeError, TypeError) fallback as-is for non-JSON inputs.
In `@rag/llm/embedding_model.py`:
- Around line 243-249: The code assumes json.loads(key) returns a dict and calls
key_obj.get(...) which raises AttributeError for non-dict JSON (e.g., a list or
string); update the try/except to validate the result type: after key_obj =
json.loads(key) check isinstance(key_obj, dict) and only then set api_key =
key_obj.get("api_key", "") and api_version = key_obj.get("api_version",
"2024-02-01"); if it's not a dict, fall back to treating key as the raw api_key
(api_key = key) and default api_version, ensuring the existing except block
still handles JSONDecodeError/TypeError.
---
Nitpick comments:
In `@rag/llm/cv_model.py`:
- Around line 309-311: The except block that falls back to treating `key` as a
raw API key is silent; change the handler for json.JSONDecodeError/TypeError to
capture the exception (e.g., `except (json.JSONDecodeError, TypeError) as e:`)
and emit a single info/warning log that the raw-key fallback was used, include
the exception message and a masked form of `key` for diagnostics, then set
`api_key = key` and `api_version = "2024-02-01"`; use the module/class logger
used elsewhere in this file (e.g., `logger` or `self.logger`) to perform the log
call.
In `@rag/llm/embedding_model.py`:
- Around line 247-249: Add a concise log inside the except
(json.JSONDecodeError, TypeError) fallback branch so we record that the raw-key
fallback was used and include minimal context for troubleshooting (e.g.,
anonymized/partial value of key and that api_version was set to "2024-02-01");
update the except block handling in embedding_model.py (the branch setting
api_key = key and api_version = "2024-02-01") to call the module/class logger
(or a provided logger variable) with a short message like "Malformed credential
payload; using raw API key fallback" plus non-sensitive context, ensuring no
full secrets are logged.
🪄 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: 6c6a3166-d786-4bb5-9538-a5cb0708a512
📒 Files selected for processing (2)
rag/llm/cv_model.pyrag/llm/embedding_model.py
Reject valid-but-non-dict JSON payloads instead of crashing on .get(), and emit warnings when falling back to a raw api_key string. Co-authored-by: Cursor <[email protected]>
|
Addressed CodeRabbit review feedback in the latest push (logging, non-dict JSON guard, consecutive header merge + tests). Ready for another look. |
1 similar comment
|
Addressed CodeRabbit review feedback in the latest push (logging, non-dict JSON guard, consecutive header merge + tests). Ready for another look. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
rag/llm/cv_model.py (1)
317-320: 🏗️ Heavy liftRoute Azure client initialization through
LLMBundleinstead of direct SDK clients.This constructor is still creating
AzureOpenAI/AsyncAzureOpenAIdirectly, which keeps this flow outside the repo’s unified LLM interface contract.As per coding guidelines,
**/*.py: "Use LLMBundle from api.db.services.llm_service as the unified interface for LLM interactions".🤖 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 317 - 320, The constructor currently instantiates AzureOpenAI and AsyncAzureOpenAI directly in __init__, bypassing the project's unified LLM interface; replace those direct SDK client creations with an LLMBundle-based initialization (import LLMBundle from api.db.services.llm_service), create or retrieve an LLMBundle instance using the provided key/base_url/api_version parameters, and obtain the sync/async client wrappers from that bundle to assign to self.client and self.async_client so the class conforms to the repo's LLM interface contract.Source: Coding guidelines
🤖 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/cv_model.py`:
- Around line 317-320: The constructor currently instantiates AzureOpenAI and
AsyncAzureOpenAI directly in __init__, bypassing the project's unified LLM
interface; replace those direct SDK client creations with an LLMBundle-based
initialization (import LLMBundle from api.db.services.llm_service), create or
retrieve an LLMBundle instance using the provided key/base_url/api_version
parameters, and obtain the sync/async client wrappers from that bundle to assign
to self.client and self.async_client so the class conforms to the repo's LLM
interface contract.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c34b1e8b-95d9-4275-a877-1c1345689afb
📒 Files selected for processing (2)
rag/llm/cv_model.pyrag/llm/embedding_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/llm/embedding_model.py
|
Thanks for the fix! One minor suggestion: This is non-blocking — the current fix works correctly. Just a thought for a follow-up refactor. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15877 +/- ##
=======================================
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:
|
Fixes #15587
Problem
AzureEmbed.__init__inrag/llm/embedding_model.pyandAzureGptV4.__init__inrag/llm/cv_model.pyboth calljson.loads(key)unconditionally: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.loadsraisesJSONDecodeError. This makes the model fail to initialize and causes document parsing/embedding to return a 500 error.Fix
Wrap
json.loadsintry/except (json.JSONDecodeError, TypeError)and fall back to using the raw string as theapi_keywith the defaultapi_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