Skip to content

fix: tolerate raw api_key string in AzureEmbed and AzureGptV4 __init__ - #15877

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
jason020818:fix/azure-embed-cv-raw-api-key
Jun 11, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
jason020818:fix/azure-embed-cv-raw-api-key

Conversation

@jason020818

@jason020818 jason020818 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

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]>
@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 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bdf94abd-bb95-42e8-a4be-8b686eb58b29

📥 Commits

Reviewing files that changed from the base of the PR and between 30ace28 and 801885a.

📒 Files selected for processing (1)
  • rag/llm/embedding_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/llm/embedding_model.py

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Azure Credential Parsing Robustness

Layer / File(s) Summary
Credential resolver and initializer updates
rag/llm/cv_model.py, rag/llm/embedding_model.py
Adds _resolve_azure_credentials(key) that attempts json.loads(key) and, if the result is a dict, extracts api_key and api_version (default "2024-02-01"). Updates AzureGptV4.__init__ and AzureEmbed.__init__ to use the helper and fall back to (key, "2024-02-01") with a logged warning on parse/type errors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15776: Applies similar defensive JSON parsing pattern to OpenRouterCV credential handling in the same file.

Suggested labels

size:S

Poem

🐰 I nibble keys with gentle care,
I sniff for JSON in the air.
If parsing fails or yields a mess,
I tuck the raw key — no distress.
Default versions hop in with flair.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Description check ❓ Inconclusive The description provides clear problem statement, fix explanation, and file list. However, it does not include the required 'Type of change' checklist from the template. Add the 'Type of change' section from the template to indicate this is a Bug Fix by checking the appropriate checkbox.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: making AzureEmbed and AzureGptV4 tolerate raw API key strings instead of requiring JSON objects.
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.

@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: 2

🧹 Nitpick comments (2)
rag/llm/embedding_model.py (1)

247-249: ⚡ Quick win

Log 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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 87b8062 and ca1141b.

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

Comment thread rag/llm/cv_model.py Resolved
Comment thread rag/llm/embedding_model.py Resolved
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]>
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 9, 2026
@jason020818

Copy link
Copy Markdown
Contributor Author

Addressed CodeRabbit review feedback in the latest push (logging, non-dict JSON guard, consecutive header merge + tests). Ready for another look.

1 similar comment
@jason020818

Copy link
Copy Markdown
Contributor Author

Addressed CodeRabbit review feedback in the latest push (logging, non-dict JSON guard, consecutive header merge + tests). Ready for another look.

@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 (1)
rag/llm/cv_model.py (1)

317-320: 🏗️ Heavy lift

Route Azure client initialization through LLMBundle instead of direct SDK clients.

This constructor is still creating AzureOpenAI/AsyncAzureOpenAI directly, 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

📥 Commits

Reviewing files that changed from the base of the PR and between ca1141b and 30ace28.

📒 Files selected for processing (2)
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/llm/embedding_model.py

@jason020818

Copy link
Copy Markdown
Contributor Author

@wangq8 Small S bugfix for #15587 — Azure credential init now tolerates raw api_key strings and non-dict JSON payloads with logging. Ready for review.

@euvre

euvre commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the fix!

One minor suggestion: _resolve_azure_credentials is defined identically in both rag/llm/embedding_model.py and rag/llm/cv_model.py. Since the same credential resolution logic now exists in three places, it might be worth extracting this into a shared utility module (e.g. rag/llm/utils.py or common/llm_utils.py) to avoid duplication and ensure a single source of truth for Azure credential parsing.

This is non-blocking — the current fix works correctly. Just a thought for a follow-up refactor.

@jason020818

Copy link
Copy Markdown
Contributor Author

@wangq8 Friendly follow-up — open ~2 days, clean merge. Tolerates raw api_key strings in AzureEmbed/AzureGptV4 __init__ (Fixes #15587). Logging + non-dict JSON guard included from review feedback. Ready when you have a moment.

@wangq8 wangq8 added the ci Continue Integration label Jun 11, 2026
@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (47fb462) to head (801885a).
⚠️ Report is 5 commits behind head on main.

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.
📢 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.

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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Error while trying to parse the document using Azure OpenAI [Bug]: Error while trying to add Azure OpenAI Model

3 participants