Skip to content

Add HuaweiCloud model provider - #15237

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/huaweicloud-provider
May 26, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/huaweicloud-provider

Conversation

@Harry-Hz-Zhang

@Harry-Hz-Zhang Harry-Hz-Zhang commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Related to #14736

This PR adds HuaweiCloud provider integration in RAGFlow.

Supported capabilities:

  • Chat / Think Chat / Stream Chat / Stream Think Chat
  • Embedding
  • Rerank
  • Model listing
  • Provider connection checking

Verified examples from the CLI:

check instance 'test' from 'HuaweiCloud';

chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

think chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

stream chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

stream think chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello';

embed text 'what is rag' 'who are you' with 'bge-m3@test@HuaweiCloud' dimension 1024;

rerank query 'what is rag' document 'rag is retrieval augmented generation' 'rag need llm' 'famous rag
project includes ragflow' with 'bge-reranker-v2-m3@test@HuaweiCloud' top 3;

list supported models from 'HuaweiCloud' 'test';

LIST MODELS FROM 'HuaweiCloud' 'test';

Type of change

  • New Feature
  • Provider integration

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 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: 01435259-ace7-4915-9cbe-07868ff60221

📥 Commits

Reviewing files that changed from the base of the PR and between d63e042 and 8f3025d.

📒 Files selected for processing (1)
  • internal/entity/models/huaweicloud.go
💤 Files with no reviewable changes (1)
  • internal/entity/models/huaweicloud.go

📝 Walkthrough

Walkthrough

Adds HuaweiCloud as a model provider: a JSON provider config, factory registration, and a HuaweiCloudModel driver implementing chat (streaming and non-stream), embeddings, rerank, model listing/check, and stubbed audio/file/task methods.

Changes

HuaweiCloud Provider

Layer / File(s) Summary
Configuration & Factory Registration
conf/models/huaweicloud.json, internal/entity/models/factory.go
HuaweiCloud provider JSON (regional base URLs, capability URL suffixes, supported models, and features for thinking/reasoning) added; factory registers "huaweicloud" and returns the new driver.
Driver Type & Initialization
internal/entity/models/huaweicloud.go (lines 1–176)
Adds HuaweiCloudModel, constructor, HTTP client and region-aware base URL resolution, authorization formatting, chat endpoint selection (including v1 mapping), and chat-config application (thinking/effort mapping).
Chat Completion & Streaming
internal/entity/models/huaweicloud.go (lines 178–388)
ChatWithMessages non-stream chat: request/response flow and reasoning extraction. ChatStreamlyWithSender SSE streaming: event scanning, delta handling for content and reasoning_content, and termination detection.
Embeddings & Reranking
internal/entity/models/huaweicloud.go (lines 390–575)
Embed posts embedding requests, validates indexed embedding responses and assembles results. Rerank posts rerank requests, parses results, applies TopN if set, and validates returned indices and scores.
Model Management & Stubs
internal/entity/models/huaweicloud.go (lines 576–670)
ListModels (GET models), CheckConnection delegates to ListModels. ASR, TTS, OCR, file parsing, task listing/detail, and Balance methods are stubbed returning "no such method" errors.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐇 I hopped through clouds of Huawei blue,
New drivers built, for chat and cue,
Streams and embeddings now take flight,
Reasoning tokens in moonlight,
A rabbit cheers this code anew.

🚥 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 clearly and concisely summarizes the main change: adding HuaweiCloud as a new model provider to the system.
Description check ✅ Passed The description covers the problem statement and includes a well-documented type of change section, with verified CLI examples demonstrating the implemented functionality.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Haruko386 Haruko386 added the ci Continue Integration label May 26, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft May 26, 2026 07:12
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review May 26, 2026 07:12

@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

🤖 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/huaweicloud.go`:
- Around line 83-100: The huaweiCloudSupportsThinkingToggle function omits
"deepseek-r1-250528" so huaweiCloudApplyChatConfig drops the thinking block;
update huaweiCloudSupportsThinkingToggle (the switch/case that checks
strings.Contains(model, ...)) to include strings.Contains(model,
"deepseek-r1-250528") in the true branch so the function returns true for that
model and the thinking/clear_thinking toggle is preserved when sending config to
Huawei Cloud.
- Around line 22-35: NewHuaweiCloudModel currently creates a single httpClient
with Timeout: 120s which causes SSE streams in ChatStreamlyWithSender (which
uses http.NewRequestWithContext) to be cut off; add a separate streaming client
(e.g., a new field StreamHTTPClient on HuaweiCloudModel) with Timeout: 0 or
another streaming-appropriate policy and a streaming-friendly Transport,
initialize it in NewHuaweiCloudModel alongside the existing httpClient, and
update ChatStreamlyWithSender to use HuaweiCloudModel.StreamHTTPClient for SSE
requests while keeping HuaweiCloudModel.httpClient for non-stream calls and
request-level deadlines.
- Around line 264-268: Remove the unreachable panic("implement me") statements
that appear immediately after unconditional returns returning a *ChatResponse
(e.g., the return &ChatResponse{Answer: &content, ReasonContent:
&reasonContent}, nil); for each function in huaweicloud.go that ends with such a
return followed by panic("implement me"), delete the panic line (or if the
function is truly unimplemented, remove the return and keep a single panic
placeholder instead) so there are no unreachable panic calls after returns.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3ba36875-2ec2-49f0-9d44-c0cd293317cc

📥 Commits

Reviewing files that changed from the base of the PR and between 036ed5b and d63e042.

📒 Files selected for processing (3)
  • conf/models/huaweicloud.json
  • internal/entity/models/factory.go
  • internal/entity/models/huaweicloud.go

Comment on lines +22 to +35
func NewHuaweiCloudModel(baseURL map[string]string, urlSuffix URLSuffix) *HuaweiCloudModel {
return &HuaweiCloudModel{
BaseURL: baseURL,
URLSuffix: urlSuffix,
httpClient: &http.Client{
Timeout: 120 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 10,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
},
},
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and display the relevant sections in the Go driver
FILE="internal/entity/models/huaweicloud.go"
if [ ! -f "$FILE" ]; then echo "Missing $FILE"; exit 1; fi

echo "=== FILE: $FILE (key ranges) ==="
wc -l "$FILE"
# Show around the constructor snippet
sed -n '1,120p' "$FILE"
echo "=== around ChatStreamlyWithSender ==="
# Print the function if present
rg -n "func \(.*\) ChatStreamlyWithSender" "$FILE" || true
# Best-effort: show a window around that function definition
START=$(rg -n "ChatStreamlyWithSender" "$FILE" | head -n1 | cut -d: -f1)
if [ -n "${START:-}" ]; then
  sed -n "$((START-30)),$((START+120))p" "$FILE"
fi

echo "=== around thinking toggle allow-list ==="
rg -n "huaweiCloudSupportsThinkingToggle|SupportsThinkingToggle|thinking" "$FILE" || true
# Show around the toggle function (if present)
TLINE=$(rg -n "huaweiCloudSupportsThinkingToggle" "$FILE" | head -n1 | cut -d: -f1 || true)
if [ -n "${TLINE:-}" ]; then
  sed -n "$((TLINE-40)),$((TLINE+80))p" "$FILE"
fi

echo "=== check for 'return' followed immediately by panic ==="
# Heuristic search: a 'return' line followed within next 3 lines by panic
python3 - <<'PY'
import re, pathlib
p = pathlib.Path("internal/entity/models/huaweicloud.go")
lines = p.read_text().splitlines()
for i,l in enumerate(lines, start=1):
    if re.search(r'\breturn\b', l):
        for j in range(i, min(i+4, len(lines))):
            if 'panic(' in lines[j-1]:
                print(f"Possible return+panic near line {i} (panic at {j}):")
                print(f"  return line {i}: {lines[i-1].strip()}")
                print(f"  panic line {j}: {lines[j-1].strip()}")
                break
PY

# Inspect the config JSON allow-lists
JSON="conf/models/huaweicloud.json"
if [ ! -f "$JSON" ]; then echo "Missing $JSON"; exit 1; fi

echo "=== FILE: $JSON (key excerpts) ==="
python3 - <<'PY'
import json
from pathlib import Path

path = Path("conf/models/huaweicloud.json")
data = json.loads(path.read_text())

# Print whether deepseek-r1-250528 exists and what thinking fields look like.
# The exact schema may vary; best-effort: scan for model id occurrences.
def walk(x, trail=""):
    if isinstance(x, dict):
        for k,v in x.items():
            yield from walk(v, f"{trail}.{k}" if trail else str(k))
    elif isinstance(x, list):
        for idx,v in enumerate(x):
            yield from walk(v, f"{trail}[{idx}]")
    else:
        yield trail, x

# Find any dict entries that contain model id strings
matches=[]
def find_models(obj, trail=""):
    if isinstance(obj, dict):
        for k,v in obj.items():
            nt = f"{trail}.{k}" if trail else str(k)
            if isinstance(v, (dict,list)):
                find_models(v, nt)
            if isinstance(v, str) and v == "deepseek-r1-250528":
                matches.append((nt, v))
    elif isinstance(obj, list):
        for i,v in enumerate(obj):
            find_models(v, f"{trail}[{i}]")

find_models(data)
print("Occurrences of deepseek-r1-250528 (paths):")
for m in matches[:50]:
    print(" ", m[0])

# Also try to locate the model object itself
def find_model_obj(obj):
    if isinstance(obj, dict):
        for k,v in obj.items():
            if isinstance(v,(dict,list)):
                r=find_model_obj(v)
                if r: return r
            if k=="id" and v=="deepseek-r1-250528":
                return obj
            if k in ("model","name","code") and v=="deepseek-r1-250528":
                return obj
    elif isinstance(obj, list):
        for it in obj:
            r=find_model_obj(it)
            if r: return r
    return None

mobj = find_model_obj(data)
if mobj:
    print("\nLikely model object for deepseek-r1-250528:")
    print(json.dumps(mobj, indent=2)[:4000])
else:
    print("\nCould not isolate a single model object for deepseek-r1-250528; dumping top-level keys:")
    print(list(data.keys()) if isinstance(data, dict) else type(data))
PY

Repository: infiniflow/ragflow

Length of output: 13212


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="internal/entity/models/huaweicloud.go"

rg -n "context\.WithTimeout|WithTimeout\(" "$FILE" || true
rg -n "NewRequestWithContext\(context\.Background\(" "$FILE" || true
rg -n "httpClient\.Timeout|httpClient:\s*&http\.Client" "$FILE" || true

# show a bit of non-stream call sites if present
for sym in ChatWithMessages Embed Rerank ListModels; do
  echo "=== around $sym ==="
  rg -n "func \\(h \\*HuaweiCloudModel\\) $sym\\b" "$FILE" || true
done

Repository: infiniflow/ragflow

Length of output: 1214


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="internal/entity/models/huaweicloud.go"

echo "=== streaming region around first ChatStreamlyWithSender stub (250-340) ==="
sed -n '230,340p' "$FILE"

echo "=== region around unreachable panic tails near 560-690 ==="
sed -n '540,710p' "$FILE"

echo "=== ensure there aren't multiple ChatStreamlyWithSender defs besides the two we saw ==="
rg -n "func \\(h \\*HuaweiCloudModel\\) ChatStreamlyWithSender\\b" "$FILE"

Repository: infiniflow/ragflow

Length of output: 8342


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="internal/entity/models/huaweicloud.go"

echo "=== streaming region around first ChatStreamlyWithSender stub (250-340) ==="
sed -n '230,340p' "$FILE"

echo "=== region around unreachable panic tails near 560-690 ==="
sed -n '540,710p' "$FILE"

echo "=== ensure there aren't multiple ChatStreamlyWithSender defs besides the two we saw ==="
rg -n "func \\(h \\*HuaweiCloudModel\\) ChatStreamlyWithSender\\b" "$FILE"

Repository: infiniflow/ragflow

Length of output: 8342


Split SSE streaming from the shared http.Client timeout
ChatStreamlyWithSender uses http.NewRequestWithContext(context.Background(), ...) and relies on the shared httpClient.Timeout: 120 * time.Second; http.Client.Timeout covers the full response-body read, so healthy SSE streams can be cut off around ~120s (while non-stream calls already use context.WithTimeout(..., nonStreamCallTimeout)). Use a separate client/timeout policy for streaming (e.g., SSE client with Timeout: 0 or a streaming-appropriate deadline) and keep the request-level deadline mechanism consistent.

🤖 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/huaweicloud.go` around lines 22 - 35,
NewHuaweiCloudModel currently creates a single httpClient with Timeout: 120s
which causes SSE streams in ChatStreamlyWithSender (which uses
http.NewRequestWithContext) to be cut off; add a separate streaming client
(e.g., a new field StreamHTTPClient on HuaweiCloudModel) with Timeout: 0 or
another streaming-appropriate policy and a streaming-friendly Transport,
initialize it in NewHuaweiCloudModel alongside the existing httpClient, and
update ChatStreamlyWithSender to use HuaweiCloudModel.StreamHTTPClient for SSE
requests while keeping HuaweiCloudModel.httpClient for non-stream calls and
request-level deadlines.

Comment on lines +83 to +100
func huaweiCloudSupportsThinkingToggle(modelName string) bool {
model := strings.ToLower(modelName)
switch {
case strings.Contains(model, "deepseek-v4-pro"),
strings.Contains(model, "deepseek-v4-flash"),
strings.Contains(model, "deepseek-v3.1"),
strings.Contains(model, "deepseek-v3.2"),
strings.Contains(model, "qwen3-235b-a22b"),
strings.Contains(model, "qwen3-32b"),
strings.Contains(model, "qwen3-30b-a3b"),
strings.Contains(model, "glm-5.1"),
strings.Contains(model, "glm-5"),
strings.Contains(model, "kimi-k2.6"):
return true
default:
return false
}
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add deepseek-r1-250528 to the thinking allow-list.

conf/models/huaweicloud.json advertises thinking / clear_thinking support for deepseek-r1-250528, but huaweiCloudSupportsThinkingToggle returns false for it. As a result, huaweiCloudApplyChatConfig drops the thinking block for that model and the user-selected toggle never reaches Huawei Cloud.

🔧 Minimal fix
 func huaweiCloudSupportsThinkingToggle(modelName string) bool {
 	model := strings.ToLower(modelName)
 	switch {
 	case strings.Contains(model, "deepseek-v4-pro"),
 		strings.Contains(model, "deepseek-v4-flash"),
 		strings.Contains(model, "deepseek-v3.1"),
 		strings.Contains(model, "deepseek-v3.2"),
+		strings.Contains(model, "deepseek-r1-250528"),
 		strings.Contains(model, "qwen3-235b-a22b"),
 		strings.Contains(model, "qwen3-32b"),
 		strings.Contains(model, "qwen3-30b-a3b"),
 		strings.Contains(model, "glm-5.1"),
 		strings.Contains(model, "glm-5"),
📝 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 huaweiCloudSupportsThinkingToggle(modelName string) bool {
model := strings.ToLower(modelName)
switch {
case strings.Contains(model, "deepseek-v4-pro"),
strings.Contains(model, "deepseek-v4-flash"),
strings.Contains(model, "deepseek-v3.1"),
strings.Contains(model, "deepseek-v3.2"),
strings.Contains(model, "qwen3-235b-a22b"),
strings.Contains(model, "qwen3-32b"),
strings.Contains(model, "qwen3-30b-a3b"),
strings.Contains(model, "glm-5.1"),
strings.Contains(model, "glm-5"),
strings.Contains(model, "kimi-k2.6"):
return true
default:
return false
}
}
func huaweiCloudSupportsThinkingToggle(modelName string) bool {
model := strings.ToLower(modelName)
switch {
case strings.Contains(model, "deepseek-v4-pro"),
strings.Contains(model, "deepseek-v4-flash"),
strings.Contains(model, "deepseek-v3.1"),
strings.Contains(model, "deepseek-v3.2"),
strings.Contains(model, "deepseek-r1-250528"),
strings.Contains(model, "qwen3-235b-a22b"),
strings.Contains(model, "qwen3-32b"),
strings.Contains(model, "qwen3-30b-a3b"),
strings.Contains(model, "glm-5.1"),
strings.Contains(model, "glm-5"),
strings.Contains(model, "kimi-k2.6"):
return true
default:
return false
}
}
🤖 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/huaweicloud.go` around lines 83 - 100, The
huaweiCloudSupportsThinkingToggle function omits "deepseek-r1-250528" so
huaweiCloudApplyChatConfig drops the thinking block; update
huaweiCloudSupportsThinkingToggle (the switch/case that checks
strings.Contains(model, ...)) to include strings.Contains(model,
"deepseek-r1-250528") in the true branch so the function returns true for that
model and the thinking/clear_thinking toggle is preserved when sending config to
Huawei Cloud.

Comment thread internal/entity/models/huaweicloud.go Resolved
@codecov

codecov Bot commented May 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (036ed5b) to head (8f3025d).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15237   +/-   ##
=======================================
  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 Sentry.
📢 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.

@Haruko386 Haruko386 left a comment

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.

done

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

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants