Repository navigation
Integrate MWS model with API support and enhance chat functionality - #17959
Conversation
- 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.
…ted configurations
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughMWS 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. ChangesMWS provider integration
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 3
🧹 Nitpick comments (3)
rag/llm/model_meta.py (1)
469-470: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse an explicit optional annotation.
base_url: str = Noneis 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 winAdd 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 raisingRuntimeError, in both_post_jsonand_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
Authorizationheader 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 valueThe inherited OpenAI clients are unused.
Base.__init__buildsOpenAIandAsyncOpenAIclients from the passed base URL.MWSChatsends every request throughaiohttpandself.chat_url, so both clients stay unused. The extramws_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
⛔ Files ignored due to path filters (1)
web/src/assets/svg/llm/mws.svgis excluded by!**/*.svg
📒 Files selected for processing (19)
conf/llm_factories.jsonconf/models/mws.jsondocs/guides/models/supported_models.mdxinternal/entity/models/factory.gointernal/entity/models/mws.gointernal/entity/models/mws_test.gorag/llm/chat_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/mws_utils.pyrag/llm/rerank_model.pytest/unit_test/rag/llm/test_mws.pyweb/src/components/svg-icon.tsxweb/src/constants/llm.tsweb/src/locales/en.tsweb/src/locales/ru.tsweb/src/pages/user-setting/setting-model/provider-schema/constants.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/local-llm-configs.ts
| 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 | ||
| } |
There was a problem hiding this comment.
📐 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.
| 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
| 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") |
There was a problem hiding this comment.
🗄️ 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 -80Repository: 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.goRepository: 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.
| 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"] |
There was a problem hiding this comment.
🩺 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 excBased 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.
| 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
There was a problem hiding this comment.
🧹 Nitpick comments (1)
rag/llm/model_meta.py (1)
475-477: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the MWS discovery path observable.
MWS.get_model_list()inheritsOpenAIAIAPICompatible.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 logapi_keyor 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
📒 Files selected for processing (7)
rag/llm/chat_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/mws_utils.pyrag/llm/rerank_model.pytest/unit_test/rag/llm/test_mws.pyweb/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
There was a problem hiding this comment.
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 winLog 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 winPreserve the final base URL segment before appending
reranking.If
base_urlomits the trailing slash,urljoinreplaces the last segment instead of appending under it. For example,https://host/v1/retrieval/nvidiabecomeshttps://host/v1/retrieval/reranking. Normalize the base URL before applyingurljoin.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
📒 Files selected for processing (4)
rag/llm/model_meta.pyrag/llm/rerank_model.pytest/unit_test/rag/llm/test_mws.pyweb/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
There was a problem hiding this comment.
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 winInclude 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 winValidate
relevance_scorebefore 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.NaNor 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 winAdd 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
📒 Files selected for processing (4)
rag/llm/model_meta.pyrag/llm/rerank_model.pytest/unit_test/rag/llm/test_mws.pytest/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
|
@nikminer, CI error: exit status 1 |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
| | 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) | |
There was a problem hiding this comment.
Could you please adjust the formatting to match the current table style?
|
@nikminer I just send message to your mail: [email protected]. Looking forward to your reply! |
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:
Changes
Provider registration
MWSin the RAGFlow model-provider catalogConfiguration
The provider accepts:
MWS API URL — project root URL in the following format:
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:
Returned models are classified into the following RAGFlow model types:
chatembeddingrerankUnsupported model types are excluded from the provider model list.
Chat completion
Added synchronous and streaming chat-completion support through:
The implementation supports:
Only fields supported by the MWS API are forwarded in requests.
Embeddings
Added embedding support through:
The implementation:
Reranking
Added reranking support through:
The implementation:
Runtime implementations
Added MWS support to both model execution paths used by RAGFlow:
Tests
Added test coverage for:
API endpoints
/openai/v1/models/openai/v1/chat/completions/openai/v1/embeddings/cohere/v2/rerankAll endpoints are resolved relative to the configured MWS project root.
How to test