Skip to content

Integrate MWS model with API support and enhance chat functionality - #17959

Merged
JinHai-CN merged 18 commits into
infiniflow:mainfrom
nikminer:feat/mws-model-provider
Aug 11, 2026
Merged

JinHai-CN merged 18 commits into
infiniflow:mainfrom
nikminer:feat/mws-model-provider

Conversation

@nikminer

@nikminer nikminer commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

What

This pull request adds MWS GPT Model Hub as a built-in model provider in RAGFlow.

The integration allows users to configure an MWS project endpoint and token, discover the models available to that project, and use supported MWS models for chat completion, embeddings, and reranking.

Why

MWS provides hosted language, embedding, and reranking models through OpenAI-compatible and Cohere-compatible APIs.

Adding MWS as a dedicated provider gives RAGFlow users:

  • Native provider selection in the Model Providers interface
  • Automatic discovery of available project models
  • Correct MWS endpoint construction
  • Support for chat, embedding, and reranking workloads
  • Provider-specific validation and error handling

Changes

Provider registration

  • Registered MWS in the RAGFlow model-provider catalog
  • Added MWS provider metadata and endpoint definitions
  • Added an MWS provider icon
  • Added English and Russian localization strings
  • Added MWS to the supported-models documentation

Configuration

The provider accepts:

  • MWS API URL — project root URL in the following format:

    https://gpt.mwsapis.ru/projects/<project>
    
  • MWS Token — bearer token used to authenticate API requests

The project URL is validated and normalized before requests are sent. Credentials, query parameters, and URL fragments are rejected when included in the project URL.

Model discovery

Available models are loaded dynamically from:

/openai/v1/models

Returned models are classified into the following RAGFlow model types:

  • chat
  • embedding
  • rerank

Unsupported model types are excluded from the provider model list.

Chat completion

Added synchronous and streaming chat-completion support through:

/openai/v1/chat/completions

The implementation supports:

  • System, user, and assistant messages
  • Temperature
  • Maximum completion tokens
  • Streaming responses
  • Streaming token-usage reporting
  • Bearer-token authentication
  • Provider response validation

Only fields supported by the MWS API are forwarded in requests.

Embeddings

Added embedding support through:

/openai/v1/embeddings

The implementation:

  • Supports batched input
  • Preserves input ordering using response indexes
  • Records token usage
  • Validates the number and indexes of returned vectors
  • Avoids sending requests for empty input

Reranking

Added reranking support through:

/cohere/v2/rerank

The implementation:

  • Sends the query and candidate documents
  • Preserves document ordering using response indexes
  • Returns relevance scores in the format expected by RAGFlow
  • Records input-token usage
  • Validates incomplete, duplicate, and invalid response indexes
  • Avoids sending requests for empty document lists

Runtime implementations

Added MWS support to both model execution paths used by RAGFlow:

  • Python LLM adapters
  • Go model driver

Tests

Added test coverage for:

  • Provider registration
  • Project URL validation and normalization
  • Bearer-token authentication
  • Dynamic model discovery
  • Model-type classification
  • Synchronous chat completion
  • Streaming chat completion
  • Streaming usage reporting
  • Embedding request and response handling
  • Reranking request and response handling
  • Empty-input handling
  • Invalid and incomplete provider responses
  • Frontend provider configuration

API endpoints

Capability Endpoint
Model discovery /openai/v1/models
Chat completion /openai/v1/chat/completions
Embeddings /openai/v1/embeddings
Reranking /cohere/v2/rerank

All endpoints are resolved relative to the configured MWS project root.

How to test

  1. Open Settings → Model Providers.
  2. Select MWS.
  3. Enter an MWS project URL and token.
  4. Verify that available models are loaded.
  5. Add a chat model and run a completion.
  6. Add an embedding model and process a test document.
  7. Add a reranking model and run a retrieval request.
  8. Verify both streaming and non-streaming chat responses.

ilarionov_n and others added 3 commits August 6, 2026 15:17
- Introduced MWS model in the LLMFactory and updated related constants.
- Added MWS API URL and token fields in localization files for English and Russian.
- Implemented MWS provider configuration in user settings, including validation for API URL and token.
- Created MWS model driver with methods for listing models, embedding, and reranking.
- Added unit tests for MWS model functionalities, including API interactions and input validations.
- Included SVG icon for MWS in the assets.
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

MWS is added as a model provider across configuration, Go drivers, Python adapters, tests, documentation, and the web settings UI. The integration supports chat, streaming, embeddings, reranking, model discovery, authentication, URL validation, and usage tracking.

Changes

MWS provider integration

Layer / File(s) Summary
Provider contracts and endpoint rules
conf/llm_factories.json, conf/models/mws.json, rag/llm/mws_utils.py, rag/llm/model_meta.py, docs/guides/models/supported_models.mdx
MWS metadata, endpoint suffixes, project URL validation, token validation, model classification, model discovery, and documentation links are added.
Go model driver and validation
internal/entity/models/factory.go, internal/entity/models/mws.go, internal/entity/models/mws_test.go
The Go driver implements model listing, chat, streaming, embeddings, reranking, connection checks, tenant instances, response validation, and usage tracking.
Python MWS adapters
rag/llm/chat_model.py, rag/llm/embedding_model.py, rag/llm/rerank_model.py, rag/llm/mws_utils.py, test/unit_test/rag/llm/test_mws.py, test/unit_test/rag/llm/test_rerank_normalization.py
Python adapters implement authenticated MWS chat, streaming, embedding, and Cohere-compatible reranking requests with response validation, ordering checks, usage tracking, and NVIDIA fallback endpoint regression coverage.
Web provider configuration
web/src/constants/llm.ts, web/src/components/svg-icon.tsx, web/src/locales/*.ts, web/src/pages/user-setting/setting-model/provider-schema/...
The web UI registers MWS metadata, icons, localized fields, model discovery, validation, documentation links, submission mapping, and configuration tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant MWSModel
  participant MWSAdapter
  participant MWSAPI
  User->>MWSModel: Select MWS model and submit request
  MWSModel->>MWSAdapter: Build chat, embedding, or rerank request
  MWSAdapter->>MWSAPI: Send authenticated request
  MWSAPI-->>MWSAdapter: Return response and usage
  MWSAdapter-->>MWSModel: Return validated result
  MWSModel-->>User: Provide model output
Loading

Possibly related PRs

Suggested labels: 🌈 python, 🧰 typescript, 🧪 test

Suggested reviewers: 07heco, lynn-inf

Poem

I’m a rabbit with an MWS key,
Chat and vectors hop with me.
Streams flow and ranks align,
URLs and tokens follow the line.
The provider joins the UI bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.42% 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 clearly identifies the MWS integration and mentions chat support, which are central parts of the changes.
Description check ✅ Passed The description explains the purpose, implementation scope, endpoints, testing, and user validation steps in sufficient detail.
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.

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.

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

🧹 Nitpick comments (3)
rag/llm/model_meta.py (1)

469-470: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use an explicit optional annotation.

base_url: str = None is an implicit Optional. Ruff reports RUF013.

♻️ Proposed fix
-    def __init__(self, api_key: str, base_url: str = None):
+    def __init__(self, api_key: str, base_url: str | None = None):
🤖 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/model_meta.py` around lines 469 - 470, Update the __init__ parameter
annotation for base_url to explicitly allow None, using Optional[str] or the
project’s preferred union syntax while preserving its default value and the
existing require_mws_token and normalize_mws_project_url calls.

Source: Linters/SAST tools

rag/llm/chat_model.py (2)

1127-1142: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging to the new MWS flows. The three new MWS adapters perform outbound HTTP calls and raise errors without any log statement, so failures carry no provider context in the logs.

  • rag/llm/chat_model.py#L1127-L1142: log the MWS chat request target and the non-200 status before raising RuntimeError, in both _post_json and _async_chat_streamly.
  • rag/llm/embedding_model.py#L895-L901: log the MWS embedding call, including the model name and batch size, and log the failure path.
  • rag/llm/rerank_model.py#L296-L307: log the MWS rerank call, including the model name and document count, and log the failure path.

Do not log the token or the Authorization header value.

As per coding guidelines: **/*.py: "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 1127 - 1142, Add provider-context logging
to the MWS outbound flows: in rag/llm/chat_model.py lines 1127-1142, update both
_post_json and _async_chat_streamly to log the request target and non-200 status
before raising RuntimeError; in rag/llm/embedding_model.py lines 895-901, log
the embedding model name, batch size, and failure path; in
rag/llm/rerank_model.py lines 296-307, log the rerank model name, document
count, and failure path. Do not log tokens or Authorization header values.

Source: Coding guidelines


1080-1092: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The inherited OpenAI clients are unused.

Base.__init__ builds OpenAI and AsyncOpenAI clients from the passed base URL. MWSChat sends every request through aiohttp and self.chat_url, so both clients stay unused. The extra mws_api_url(base_url, "openai/v1") call exists only to feed them. Consider setting the required attributes directly, or document why the base constructor is still needed.

🤖 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 1080 - 1092, The MWSChat initializer
creates unused OpenAI clients through the inherited constructor; update
MWSChat.__init__ to initialize only the attributes required by its
aiohttp/self.chat_url request flow, including token and model state, without
calling Base.__init__, unless a documented inherited requirement makes that call
necessary. Remove the redundant mws_api_url(base_url, "openai/v1") usage while
preserving the existing authentication and chat URL setup.
🤖 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 `@internal/entity/models/mws_test.go`:
- Around line 38-58: Replace t.Fatalf with t.Errorf in decodeMWSRequest and the
other cited assertions executed within HTTP handler goroutines, including the
checks around lines 76, 79, 83, 108, 121, 155, 167, 208, 213, 234, and 244.
Preserve each existing validation message and allow handlers to continue so they
can write their responses.

In `@internal/entity/models/mws.go`:
- Around line 78-90: Update MWSModel endpoint construction and its request
methods to read the relevant paths from m.baseModel.URLSuffix instead of
hardcoded values such as "openai/v1/models". Validate that each required
configured suffix exists before building the URL, and preserve the existing
error propagation behavior for invalid configuration.

In `@rag/llm/chat_model.py`:
- Around line 1183-1194: Update the SSE parsing loop around json.loads(data) to
catch json.JSONDecodeError and raise the provider-specific error instead,
chaining the original exception with “from exc”; preserve the existing handling
for valid events, [DONE], and usage tracking.

---

Nitpick comments:
In `@rag/llm/chat_model.py`:
- Around line 1127-1142: Add provider-context logging to the MWS outbound flows:
in rag/llm/chat_model.py lines 1127-1142, update both _post_json and
_async_chat_streamly to log the request target and non-200 status before raising
RuntimeError; in rag/llm/embedding_model.py lines 895-901, log the embedding
model name, batch size, and failure path; in rag/llm/rerank_model.py lines
296-307, log the rerank model name, document count, and failure path. Do not log
tokens or Authorization header values.
- Around line 1080-1092: The MWSChat initializer creates unused OpenAI clients
through the inherited constructor; update MWSChat.__init__ to initialize only
the attributes required by its aiohttp/self.chat_url request flow, including
token and model state, without calling Base.__init__, unless a documented
inherited requirement makes that call necessary. Remove the redundant
mws_api_url(base_url, "openai/v1") usage while preserving the existing
authentication and chat URL setup.

In `@rag/llm/model_meta.py`:
- Around line 469-470: Update the __init__ parameter annotation for base_url to
explicitly allow None, using Optional[str] or the project’s preferred union
syntax while preserving its default value and the existing require_mws_token and
normalize_mws_project_url calls.
🪄 Autofix

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 Plus

Run ID: d437683d-2e8d-4b08-880b-0c949c706035

📥 Commits

Reviewing files that changed from the base of the PR and between f532f27 and 98dabf7.

⛔ Files ignored due to path filters (1)
  • web/src/assets/svg/llm/mws.svg is excluded by !**/*.svg
📒 Files selected for processing (19)
  • conf/llm_factories.json
  • conf/models/mws.json
  • docs/guides/models/supported_models.mdx
  • internal/entity/models/factory.go
  • internal/entity/models/mws.go
  • internal/entity/models/mws_test.go
  • rag/llm/chat_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/mws_utils.py
  • rag/llm/rerank_model.py
  • test/unit_test/rag/llm/test_mws.py
  • web/src/components/svg-icon.tsx
  • web/src/constants/llm.ts
  • web/src/locales/en.ts
  • web/src/locales/ru.ts
  • web/src/pages/user-setting/setting-model/provider-schema/constants.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.ts

Comment on lines +38 to +58
func decodeMWSRequest(t *testing.T, request *http.Request) map[string]any {
t.Helper()
if request.Method != http.MethodPost {
t.Fatalf("unexpected method: %s", request.Method)
}
if request.Header.Get("Authorization") != "Bearer token" {
t.Fatalf("unexpected authorization: %q", request.Header.Get("Authorization"))
}
if request.Header.Get("Content-Type") != "application/json" {
t.Fatalf("unexpected content type: %q", request.Header.Get("Content-Type"))
}
body, err := io.ReadAll(request.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
var payload map[string]any
if err = json.Unmarshal(body, &payload); err != nil {
t.Fatalf("decode request body: %v", err)
}
return payload
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use t.Errorf inside HTTP handlers.

decodeMWSRequest runs inside the httptest handler goroutine. t.Fatalf calls runtime.Goexit on that goroutine, so the handler stops without writing a response and the test goroutine can block or report a misleading failure. The same pattern appears at lines 76, 79, 83, 108, 121, 155, 167, 208, 213, 234, and 244.

💚 Proposed fix for the helper
 func decodeMWSRequest(t *testing.T, request *http.Request) map[string]any {
 	t.Helper()
 	if request.Method != http.MethodPost {
-		t.Fatalf("unexpected method: %s", request.Method)
+		t.Errorf("unexpected method: %s", request.Method)
 	}
 	if request.Header.Get("Authorization") != "Bearer token" {
-		t.Fatalf("unexpected authorization: %q", request.Header.Get("Authorization"))
+		t.Errorf("unexpected authorization: %q", request.Header.Get("Authorization"))
 	}
 	if request.Header.Get("Content-Type") != "application/json" {
-		t.Fatalf("unexpected content type: %q", request.Header.Get("Content-Type"))
+		t.Errorf("unexpected content type: %q", request.Header.Get("Content-Type"))
 	}
 	body, err := io.ReadAll(request.Body)
 	if err != nil {
-		t.Fatalf("read request body: %v", err)
+		t.Errorf("read request body: %v", err)
+		return nil
 	}
 	var payload map[string]any
 	if err = json.Unmarshal(body, &payload); err != nil {
-		t.Fatalf("decode request body: %v", err)
+		t.Errorf("decode request body: %v", err)
 	}
 	return payload
 }

Based on learnings: inside an http.HandlerFunc in Go tests, use t.Errorf instead of t.Fatalf, because t.Fatalf triggers runtime.Goexit() only on the handler goroutine.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func decodeMWSRequest(t *testing.T, request *http.Request) map[string]any {
t.Helper()
if request.Method != http.MethodPost {
t.Fatalf("unexpected method: %s", request.Method)
}
if request.Header.Get("Authorization") != "Bearer token" {
t.Fatalf("unexpected authorization: %q", request.Header.Get("Authorization"))
}
if request.Header.Get("Content-Type") != "application/json" {
t.Fatalf("unexpected content type: %q", request.Header.Get("Content-Type"))
}
body, err := io.ReadAll(request.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
var payload map[string]any
if err = json.Unmarshal(body, &payload); err != nil {
t.Fatalf("decode request body: %v", err)
}
return payload
}
func decodeMWSRequest(t *testing.T, request *http.Request) map[string]any {
t.Helper()
if request.Method != http.MethodPost {
t.Errorf("unexpected method: %s", request.Method)
}
if request.Header.Get("Authorization") != "Bearer token" {
t.Errorf("unexpected authorization: %q", request.Header.Get("Authorization"))
}
if request.Header.Get("Content-Type") != "application/json" {
t.Errorf("unexpected content type: %q", request.Header.Get("Content-Type"))
}
body, err := io.ReadAll(request.Body)
if err != nil {
t.Errorf("read request body: %v", err)
return nil
}
var payload map[string]any
if err = json.Unmarshal(body, &payload); err != nil {
t.Errorf("decode request body: %v", err)
}
return payload
}
🤖 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 `@internal/entity/models/mws_test.go` around lines 38 - 58, Replace t.Fatalf
with t.Errorf in decodeMWSRequest and the other cited assertions executed within
HTTP handler goroutines, including the checks around lines 76, 79, 83, 108, 121,
155, 167, 208, 213, 234, and 244. Preserve each existing validation message and
allow handlers to continue so they can write their responses.

Source: Learnings

Comment on lines +78 to +90
func (m *MWSModel) endpoint(apiConfig *APIConfig, endpoint string) (string, error) {
if err := m.baseModel.APIConfigCheck(apiConfig); err != nil {
return "", err
}
baseURL, err := m.baseModel.GetBaseURL(apiConfig)
if err != nil {
return "", err
}
return buildMWSEndpoint(baseURL, endpoint)
}

func (m *MWSModel) ListModels(ctx context.Context, apiConfig *APIConfig) ([]ListModelResponse, error) {
endpoint, err := m.endpoint(apiConfig, "openai/v1/models")

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check how other model drivers consume URLSuffix for endpoint construction.
set -euo pipefail

rg -nP -C4 '\bURLSuffix\b' internal/entity/models | head -120
rg -nP -C3 'GetURLSuffix|urlSuffix\.' internal/entity/models | head -80

Repository: infiniflow/ragflow

Length of output: 8545


🏁 Script executed:

#!/bin/bash
# Description: Inspect model API contract and endpoint suffix usage across driver implementations.
set -euo pipefail

echo "== URLSuffix definition and New functions =="
rg -n 'type URLSuffix|func New[A-Za-z0-9_]+Model\(|baseModel: BaseModel|URLSuffix:' internal/entity/models -C3

echo
echo "== URLSuffix reference lines =="
rg -n '\bURLSuffix\b' internal/entity/models --glob '*.go' -C2

echo
echo "== conf model suffix definitions =="
python3 - <<'PY'
import json, pathlib
for path in sorted(pathlib.Path('conf/models').glob('*.json')):
    data=json.loads(path.read_text())
    url=data.get('url_suffix')
    if url:
        print(path)
        for k,v in url.items():
            print(f' {k}: {v}')
PY

echo
echo "== mws implementation outline and relevant reads =="
sed -n '1,120p' internal/entity/models/mws.go
rg -n 'buildMWSEndpoint|ListModels|Rerank|Embed|Chat|URLSuffix' internal/entity/models/mws.go

Repository: infiniflow/ragflow

Length of output: 50375


Use URLSuffix for MWS endpoint construction.

conf/models/mws.json declares url_suffix.models, chat, embedding, and rerank, but this driver builds the paths with hardcoded suffixes and never reads m.baseModel.URLSuffix. Use the configured suffixes with validation so configuration changes control the requested paths; matching the current default is not enough.

🤖 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 `@internal/entity/models/mws.go` around lines 78 - 90, Update MWSModel endpoint
construction and its request methods to read the relevant paths from
m.baseModel.URLSuffix instead of hardcoded values such as "openai/v1/models".
Validate that each required configured suffix exists before building the URL,
and preserve the existing error propagation behavior for invalid configuration.

Comment thread rag/llm/chat_model.py
Comment on lines +1183 to +1194
async for raw_line in response.content:
line = raw_line.decode("utf-8").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
event = json.loads(data)
usage = usage_from_response(event)
if usage["total_tokens"]:
self.last_usage = usage
reported_tokens = usage["total_tokens"]

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Wrap the SSE JSON parse error.

json.loads(data) raises json.JSONDecodeError for any malformed event, and the raw parser error reaches the caller. Wrap it in a provider-specific error and chain the cause.

🛡️ Proposed fix
                     if data == "[DONE]":
                         break
-                    event = json.loads(data)
+                    try:
+                        event = json.loads(data)
+                    except json.JSONDecodeError as exc:
+                        raise ValueError(
+                            f"MWS chat stream returned malformed JSON: {data[:200]}"
+                        ) from exc

Based on learnings: in rag/llm Python code, when catching a JSON parsing exception and re-raising a domain-specific error, use raise ... from exc to preserve the original cause.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async for raw_line in response.content:
line = raw_line.decode("utf-8").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
event = json.loads(data)
usage = usage_from_response(event)
if usage["total_tokens"]:
self.last_usage = usage
reported_tokens = usage["total_tokens"]
async for raw_line in response.content:
line = raw_line.decode("utf-8").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
try:
event = json.loads(data)
except json.JSONDecodeError as exc:
raise ValueError(
f"MWS chat stream returned malformed JSON: {data[:200]}"
) from exc
usage = usage_from_response(event)
if usage["total_tokens"]:
self.last_usage = usage
reported_tokens = usage["total_tokens"]
🤖 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 1183 - 1194, Update the SSE parsing loop
around json.loads(data) to catch json.JSONDecodeError and raise the
provider-specific error instead, chaining the original exception with “from
exc”; preserve the existing handling for valid events, [DONE], and usage
tracking.

Source: Learnings

@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/model_meta.py (1)

475-477: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the MWS discovery path observable.

MWS.get_model_list() inherits OpenAIAIAPICompatible.get_model_list(), which does not log the discovery call. Add structured logs for the request, validation or request failures, and the returned result count. Do not log api_key or the bearer header.

🤖 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/model_meta.py` around lines 475 - 477, Add structured observability
to MWS.get_model_list, or the nearest MWS-specific discovery flow around
_get_model_list_url, covering the outgoing request, validation/request failures,
and the number of returned models. Reuse existing logging conventions and ensure
api_key and bearer headers are never included in log fields or messages.

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/model_meta.py`:
- Around line 475-477: Add structured observability to MWS.get_model_list, or
the nearest MWS-specific discovery flow around _get_model_list_url, covering the
outgoing request, validation/request failures, and the number of returned
models. Reuse existing logging conventions and ensure api_key and bearer headers
are never included in log fields or messages.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 905d5f19-5d1d-4568-bbc5-f678b74bcc7d

📥 Commits

Reviewing files that changed from the base of the PR and between 0366eed and 51a5e3f.

📒 Files selected for processing (7)
  • rag/llm/chat_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/mws_utils.py
  • rag/llm/rerank_model.py
  • test/unit_test/rag/llm/test_mws.py
  • web/src/locales/en.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • web/src/locales/en.ts
  • rag/llm/embedding_model.py
  • rag/llm/rerank_model.py
  • rag/llm/mws_utils.py
  • test/unit_test/rag/llm/test_mws.py
  • rag/llm/chat_model.py

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rag/llm/rerank_model.py (2)

206-210: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Log use of the generic fallback endpoint.

Add a safe structured log event when this fallback path is selected. This is a new execution path and needs operational visibility. Do not log key.

🤖 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/rerank_model.py` around lines 206 - 210, Add a safe structured log
event immediately after the generic fallback endpoint is assigned in the
reranking model initialization path, using the existing logger and including
relevant non-sensitive context such as the selected endpoint or model. Do not
include the API key (`key`) in the event or its fields.

Source: Coding guidelines


206-210: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve the final base URL segment before appending reranking.

If base_url omits the trailing slash, urljoin replaces the last segment instead of appending under it. For example, https://host/v1/retrieval/nvidia becomes https://host/v1/retrieval/reranking. Normalize the base URL before applying urljoin.

Proposed fix
-        self.base_url = urljoin(base_url, "reranking")
+        self.base_url = urljoin(f"{base_url.rstrip('/')}/", "reranking")
🤖 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/rerank_model.py` around lines 206 - 210, Normalize base_url to
include a trailing slash before the urljoin call assigning self.base_url, so the
existing final path segment is preserved when appending "reranking". Keep the
default endpoint behavior unchanged for URLs that already end with a slash.
🤖 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/model_meta.py`:
- Around line 545-546: Update the aiohttp ClientSession construction in the MWS
discovery request to pass the existing 30-second timeout explicitly, ensuring
the session.get call within the discovery flow respects that timeout while
preserving the current authorization headers and response handling.

---

Outside diff comments:
In `@rag/llm/rerank_model.py`:
- Around line 206-210: Add a safe structured log event immediately after the
generic fallback endpoint is assigned in the reranking model initialization
path, using the existing logger and including relevant non-sensitive context
such as the selected endpoint or model. Do not include the API key (`key`) in
the event or its fields.
- Around line 206-210: Normalize base_url to include a trailing slash before the
urljoin call assigning self.base_url, so the existing final path segment is
preserved when appending "reranking". Keep the default endpoint behavior
unchanged for URLs that already end with a slash.
🪄 Autofix

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 Plus

Run ID: 1d6d713a-ce62-43b1-a57e-f3d9039e1ccb

📥 Commits

Reviewing files that changed from the base of the PR and between 51a5e3f and f16d189.

📒 Files selected for processing (4)
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • test/unit_test/rag/llm/test_mws.py
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.ts
💤 Files with no reviewable changes (1)
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit_test/rag/llm/test_mws.py

Comment thread rag/llm/model_meta.py Resolved

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rag/llm/rerank_model.py (2)

344-349: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include query tokens in MWS usage accounting.

The request sends query, but the returned count sums only the truncated documents. This under-reports every non-empty rerank request by the query token count.

Proposed fix
-return rank, sum(num_tokens_from_string(document) for document in documents)
+return rank, num_tokens_from_string(query) + sum(
+    num_tokens_from_string(document) for document in documents
+)
🤖 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/rerank_model.py` around lines 344 - 349, Update the MWS usage-token
calculation in the rerank method to include the token count for the submitted
query in addition to the truncated documents. Preserve the existing rank
validation and return structure while ensuring non-empty requests report query
plus document tokens.

344-349: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate relevance_score before assigning it.

The index validation is strict, but item["relevance_score"] is assigned without checking its type or finiteness. Missing or invalid values raise inconsistent errors. NaN or infinity can propagate into the ranking array.

Proposed fix
+            score = item.get("relevance_score")
+            if (
+                not isinstance(score, (int, float))
+                or isinstance(score, bool)
+                or not np.isfinite(score)
+            ):
+                raise ValueError(f"unexpected MWS rerank score: {score}")
             seen.add(index)
-            rank[index] = item["relevance_score"]
+            rank[index] = score
🤖 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/rerank_model.py` around lines 344 - 349, In the MWS rerank result
processing before the assignment to rank[index] in the visible reranking method,
validate that item["relevance_score"] exists, is numeric, and is finite; raise
the method’s consistent validation error for missing or invalid values, and only
then store it in rank[index].
🧹 Nitpick comments (1)
rag/llm/rerank_model.py (1)

300-349: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add safe provider-context logging to the MWS rerank flow.

This new flow performs an outbound request and can fail during HTTP, JSON, or response validation, but it emits no MWS-specific diagnostic. Log the operation, endpoint, model, document count, and failure stage. Do not log the token, Authorization, query, or document contents.

As per coding guidelines, **/*.py: "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/rerank_model.py` around lines 300 - 349, Add provider-context logging
in MWSRerank._compute_rank for the outbound rerank operation, including the
endpoint, model name, and document count while excluding tokens, authorization
headers, queries, and document contents. Track and log the failure stage
separately for the HTTP request, JSON parsing, and response validation, then
re-raise the original exception unchanged. Use the project’s established logger
and ensure endpoint logging cannot expose credentials.

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/rerank_model.py`:
- Around line 204-219: The fallback logging in the rerank model initializer
records values before model-specific endpoint and name overrides. Move the
nvidia_rerank_fallback_endpoint_assigned event into the actual fallback branch,
or emit it after all overrides, so it logs the final base_url and model_name;
add a regression test covering nvidia/nv-rerankqa-mistral-4b-v3.

---

Outside diff comments:
In `@rag/llm/rerank_model.py`:
- Around line 344-349: Update the MWS usage-token calculation in the rerank
method to include the token count for the submitted query in addition to the
truncated documents. Preserve the existing rank validation and return structure
while ensuring non-empty requests report query plus document tokens.
- Around line 344-349: In the MWS rerank result processing before the assignment
to rank[index] in the visible reranking method, validate that
item["relevance_score"] exists, is numeric, and is finite; raise the method’s
consistent validation error for missing or invalid values, and only then store
it in rank[index].

---

Nitpick comments:
In `@rag/llm/rerank_model.py`:
- Around line 300-349: Add provider-context logging in MWSRerank._compute_rank
for the outbound rerank operation, including the endpoint, model name, and
document count while excluding tokens, authorization headers, queries, and
document contents. Track and log the failure stage separately for the HTTP
request, JSON parsing, and response validation, then re-raise the original
exception unchanged. Use the project’s established logger and ensure endpoint
logging cannot expose credentials.
🪄 Autofix

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 Plus

Run ID: 3fbf580f-6b84-419d-b6fd-264b63e89f0a

📥 Commits

Reviewing files that changed from the base of the PR and between f16d189 and 98a7925.

📒 Files selected for processing (4)
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • test/unit_test/rag/llm/test_mws.py
  • test/unit_test/rag/llm/test_rerank_normalization.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • rag/llm/model_meta.py
  • test/unit_test/rag/llm/test_mws.py

Comment thread rag/llm/rerank_model.py Resolved
@JinHai-CN JinHai-CN added the ci Continue Integration label Aug 10, 2026
@JinHai-CN

Copy link
Copy Markdown
Member

@nikminer, CI error:
┃ ruff-format ❯
Would reformat: rag/llm/chat_model.py
Would reformat: rag/llm/embedding_model.py
Would reformat: rag/llm/model_meta.py
Would reformat: rag/llm/mws_utils.py
Would reformat: rag/llm/rerank_model.py
Would reformat: test/unit_test/rag/llm/test_mws.py
6 files would be reformatted, 1 file already formatted

exit status 1

@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (dd52dee) to head (ecd948f).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17959   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

Comment thread docs/guides/models/supported_models.mdx Outdated
| Mistral | `https://mistral.ai` |
| ModelScope | `https://www.modelscope.cn` |
| Moonshot | `https://www.moonshot.cn` |
| MWS | [Chat and Embedding](https://mws.ru/docs/cloud-platform/gpt/general/inference-text.html) / [Reranking](https://mws.ru/docs/cloud-platform/gpt/general/inference-rerank.html) |

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please adjust the formatting to match the current table style?

@JinHai-CN
JinHai-CN requested review from Lynn-Inf and cike8899 August 11, 2026 09:39
@cike8899
cike8899 requested a review from dcc123456 August 11, 2026 09:47

@Lynn-Inf Lynn-Inf 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.

LGTM

@JinHai-CN
JinHai-CN merged commit 8bd5768 into infiniflow:main Aug 11, 2026
5 checks passed
@JinHai-CN

Copy link
Copy Markdown
Member

@nikminer I just send message to your mail: [email protected]. Looking forward to your reply!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants