Skip to content

fix(llm): tolerate raw api_key string in Azure-OpenAI chat init (#15587) - #15604

Closed
Rene0422 wants to merge 4 commits into
infiniflow:mainfrom
Rene0422:fix/azure-openai-add-provider-json-decode-crash
Closed

Rene0422 wants to merge 4 commits into
infiniflow:mainfrom
Rene0422:fix/azure-openai-add-provider-json-decode-crash

Conversation

@Rene0422

@Rene0422 Rene0422 commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

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 key was always a JSON blob — but the
verify-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(...) at
api/apps/services/provider_api_service.py:376:

mdl = ChatModel["Azure-OpenAI"](api_key, llm["llm_name"],
                                base_url=base_url, **extra)

api_key here is the raw user-typed string extracted from
the request body at
api/apps/restful_apis/provider_api.py:335. It is NOT the JSON
blob ({"api_key": "...", "api_version": "..."}) that the
runtime path packs into the model_instance row after save.

The Azure branch at rag/llm/chat_model.py:1372-1374 did:

self.api_key = json.loads(key).get("api_key", "")
self.api_version = json.loads(key).get("api_version", "2024-02-01")

— so json.loads("sk-abc123") consumed the first 4 chars as a
JSON string literal and choked on the rest with
Extra data: line 1 column 5 (char 4) — exactly the reporter's
traceback.

The char 4 is the giveaway: it's where the parser had finished
the 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:

try:
    key_obj = json.loads(key) if isinstance(key, str) else key
except (json.JSONDecodeError, TypeError):
    key_obj = None
if isinstance(key_obj, dict):
    self.api_key = key_obj.get("api_key", "")
    self.api_version = key_obj.get("api_version", "2024-02-01")
else:
    self.api_key = key
    self.api_version = "2024-02-01"

So:

  • dict / parseable JSON blob in → unpack api_key +
    api_version (runtime path, unchanged behaviour)
  • raw string in → use it as api_key, default version
    (verify path, previously crashed)
  • empty / malformed / non-string → use as api_key, default
    version (defensive)

Validation done in this sandbox

Drove the new branch logic in-process against five input
shapes the route exercises:

Shape Result
Raw key "sk-abc123" (the repro) api_key="sk-abc123", default version
JSON blob from runtime save unpacks both fields correctly
Bare dict (some paths skip json.dumps) unpacks both fields correctly
Empty string empty key, default version
Partial / malformed JSON treated as raw key, default version

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-1371 has the same
json.loads(key).get(...) anti-pattern. The reporter only hit it
with Azure, and OpenRouter's verify path may pack
provider_order differently from the runtime save shape. Fixing
it 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

  • Repro the original crash: revert this commit, restart
    the server, then POST /api/v1/providers/Azure-OpenAI/instances
    with {"instance_name": "...", "api_key": "<raw-azure-key>", "base_url": "https://<...>.openai.azure.com/"}. Server log
    should show JSONDecodeError: Extra data: line 1 column 5 (char 4) from chat_model.py.
  • Re-apply this commit: same request now reaches
    verify_api_key cleanly. The "Verify" button in the
    Add-Azure-OpenAI modal should turn green for a valid key
    and report Fail to access ... for an invalid key —
    no traceback either way.
  • Runtime path regression: an existing Azure provider
    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.
  • Custom api_version: add an Azure provider with
    api_version=2024-08-01-preview (or whatever the FE
    packs). It should be honoured rather than overwritten by
    the default.
  • uv run pytest — the change is localised to one branch in
    one constructor; no existing test should change behaviour.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 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: b675896f-9382-4c8c-a42a-71d2b992eb77

📥 Commits

Reviewing files that changed from the base of the PR and between 7ba87f1 and 62bc9c7.

📒 Files selected for processing (1)
  • rag/llm/chat_model.py
💤 Files with no reviewable changes (1)
  • rag/llm/chat_model.py

📝 Walkthrough

Walkthrough

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

Changes

Azure OpenAI Provider Key Initialization

Layer / File(s) Summary
Azure OpenAI key parsing
rag/llm/chat_model.py
Replaces unconditional json.loads(key).get(...) with guarded try/except logic that safely handles both JSON and raw string API keys; extracts api_key and api_version when JSON parses successfully, otherwise treats key as raw api_key and uses default api_version of "2024-02-01".

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Possibly related PRs

  • infiniflow/ragflow#14707: Addresses similar JSONDecodeError issues around non-JSON api_key handling for provider auth.

Suggested labels

size:XS

Suggested reviewers

  • wangq8
  • Lynn-Inf

Poem

🐰 I sniffed the keys both raw and parsed,
I hopped through code where errors used to guard,
A gentle try/except now saves the day,
No more crashes on the Azure way,
Tiny fix — calm logs and hooray! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically describes the main fix: making Azure-OpenAI chat initialization tolerate raw API key strings instead of only JSON blobs.
Description check ✅ Passed The description comprehensively covers the problem, root cause analysis, fix implementation, validation results, and test plan, fully matching the template requirements.
Linked Issues check ✅ Passed The code changes directly address issue #15587: the try-except block now handles raw API key strings gracefully during verify-api-key flow without JSONDecodeError, while maintaining backward compatibility with stored JSON blobs.
Out of Scope Changes check ✅ Passed All changes in rag/llm/chat_model.py are tightly scoped to the Azure-OpenAI provider initialization logic to fix the reported issue, with no extraneous modifications to unrelated code.

✏️ 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.

🧹 Nitpick comments (1)
rag/llm/chat_model.py (1)

1381-1390: ⚡ Quick win

Defensive 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 except swallows JSONDecodeError/TypeError silently. 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 = None

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/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

📥 Commits

Reviewing files that changed from the base of the PR and between 67c3e73 and 2283bdc.

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

@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 3, 2026
@wangq8 wangq8 added the ci Continue Integration label Jun 4, 2026
@wangq8
wangq8 marked this pull request as draft June 4, 2026 01:52
@wangq8
wangq8 marked this pull request as ready for review June 4, 2026 01:53
@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 (62bc9c7).
⚠️ Report is 16 commits behind head on main.

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

@meetcharan-practice

Copy link
Copy Markdown

Can someone merge this PR please? Thanks in advance.

@wangq8

wangq8 commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

dup of this PR: #15877

@wangq8 wangq8 closed this Jun 11, 2026
wangq8 added a commit that referenced this pull request Jun 11, 2026
#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]>
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 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 add Azure OpenAI Model

3 participants