Skip to content

go: add Qiniu model provider - #15280

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/qiniu-provider
May 27, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/qiniu-provider

Conversation

@Harry-Hz-Zhang

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

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Related to #14736

This PR adds Qiniu provider integration for the Go model driver layer in RAGFlow.

Supported capabilities:

  • Chat
  • Think Chat
  • Stream Chat
  • Stream Think Chat
  • Model listing
  • Provider configuration and factory registration

Verified examples from the CLI:

login user '***' password '***';

ADD PROVIDER 'qiniu';

CREATE PROVIDER 'qiniu' INSTANCE 'test' KEY '***';

chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello';

think chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello';

stream chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello, what are you';

stream think chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello, what are you';

stream think chat with 'qwen3-max-2026-01-23@test@qiniu' message 'hello, what are you';

LIST MODELS FROM 'qiniu' '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 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR integrates Qiniu as a new model provider. It adds provider configuration defining URLs and models, wires the provider into the factory dispatcher, implements the QiniuModel driver with synchronous and streaming chat methods, thinking/reasoning mode configuration, and model listing capability.

Changes

Qiniu Model Provider Integration

Layer / File(s) Summary
Configuration and Factory Wiring
conf/models/qiniu.json, internal/entity/models/factory.go
Qiniu provider configuration defines base API URL, endpoint suffixes, and a model catalog with optional max_tokens, model_types, and thinking settings; factory dispatch wiring routes the "qiniu" provider name to instantiate a QiniuModel driver.
Driver Type and Initialization
internal/entity/models/qiniu.go (struct & constructor)
QiniuModel struct holds region-aware BaseURL map, URLSuffix, and a configured HTTP client; NewQiniuModel constructor and NewInstance factory method initialize driver instances; Name() method returns provider identifier.
Chat with Streaming and Thinking Support
internal/entity/models/qiniu.go (chat methods & config)
applyQiniuThinkingConfig conditionally enables or configures reasoning mode based on model membership in allow/deny sets and ChatConfig thinking settings; ChatWithMessages validates inputs, builds region-specific URL, marshals request with message pairs and sampling parameters, applies thinking config, sends authenticated JSON POST, parses response to extract content and optional reasoning_content; ChatStreamlyWithSender sends streaming POST, reads SSE-like events line-by-line with data: prefix filtering, unmarshals each delta to extract reasoning_content and content, forwards updates via sender callback with explicit reasoning/content separation, handles [DONE] termination, and returns scanner errors.
Model Operations and Unsupported Method Stubs
internal/entity/models/qiniu.go (ListModels & stubs)
ListModels validates API key, builds region-specific endpoint URL, performs authenticated GET, parses response data array, and returns extracted model ID list; remaining driver methods (Embed, Rerank, TranscribeAudio, AudioSpeech, OCRFile, ParseFile, Balance, CheckConnection, ListTasks, ShowTask) return "no such method" errors identifying the driver.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant QiniuModel
    participant QiniuAPI as Qiniu HTTP API
    participant Sender as Sender Callback
    
    Caller->>QiniuModel: ChatStreamlyWithSender(modelName, messages, apiConfig, chatConfig, sender)
    Note over QiniuModel: Validate API key & messages
    QiniuModel->>QiniuModel: applyQiniuThinkingConfig(request)
    QiniuModel->>QiniuAPI: POST with stream: true (Bearer auth)
    activate QiniuAPI
    QiniuAPI-->>QiniuModel: 200 + streaming body
    deactivate QiniuAPI
    Note over QiniuModel: Scan response line-by-line
    loop For each data: event
        QiniuModel->>QiniuModel: Unmarshal delta (reasoning_content, content)
        alt Has reasoning_content
            QiniuModel->>Sender: sender(nil, &reasoning_content)
        end
        alt Has content
            QiniuModel->>Sender: sender(&content, nil)
        end
    end
    Note over QiniuModel: On [DONE] termination
    QiniuModel->>Sender: sender(nil, nil) with "[DONE]" marker
    QiniuModel-->>Caller: error (if any)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#14832: Adds Baichuan provider with similar factory dispatch and driver implementation pattern.
  • infiniflow/ragflow#15237: Extends factory dispatch to wire HuaweiCloud provider driver using the same provider registration approach.
  • infiniflow/ragflow#14623: Adds Nvidia provider with parallel synchronous/streaming chat logic and thinking mode handling.

Suggested labels

feature, provider-integration

Suggested reviewers

  • Haruko386

Poem

🐰 Qiniu joins the model zoo,
With streams of thought and reason too,
Factory routes the calls with care,
Chat and models flowing fair,
Thinking deep, response so quick! 🚀

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding Qiniu as a new model provider to the Go codebase.
Description check ✅ Passed The PR description includes the required template sections with clear problem statement, supported capabilities, verified examples, and change type designation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label May 27, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft May 27, 2026 03:47
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review May 27, 2026 03:47

@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/qiniu.go`:
- Around line 334-337: The loop that calls scanner.Scan() currently logs the
full payload via common.Info(line), which can leak sensitive data and bloat
logs; remove that raw logging and either delete the common.Info(line) call or
replace it with a non-sensitive log such as common.Debug or common.Info that
only records metadata (e.g., "stream chunk received", length: len(line), or a
safely truncated/redacted snippet) so the raw contents of the variable line are
never logged; update the scanner.Scan() loop in qiniu.go (the block referencing
variable line and common.Info) accordingly.
- Around line 237-242: When parsing messageMap in the code path guarded by
chatModelConfig and chatModelConfig.Thinking, do not return an error if
"reasoning_content" is absent or not a string; instead attempt to cast
messageMap["reasoning_content"] to string and if the cast fails set
reasonContent = "" (or leave it nil/empty) and continue processing so valid
"content" does not cause the whole sync to fail; update the block around
reasonContent, messageMap, chatModelConfig.Thinking to tolerate missing/invalid
reasoning_content and only use it when present and correctly typed.
- Around line 144-149: The code builds url := fmt.Sprintf("%s/%s",
q.BaseURL[region], q.URLSuffix.Chat) without verifying that q.BaseURL has an
entry for the computed region, which can cause opaque runtime errors; update the
ChatWithMessages flow to check that baseURL, e.g. base, exists for the chosen
region (lookup q.BaseURL[region] into a variable), return a clear configuration
error if missing, and only then build the URL using base and q.URLSuffix.Chat
(mirroring the validation already used for stream/list paths).
🪄 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: 26a9e3f8-057b-44af-a491-be98d8872261

📥 Commits

Reviewing files that changed from the base of the PR and between 187dc8a and 1d9944e.

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

Comment on lines +144 to +149
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", q.BaseURL[region], q.URLSuffix.Chat)

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 | 🟡 Minor | ⚡ Quick win

Validate base URL in sync chat like stream/list paths do.

ChatWithMessages directly uses q.BaseURL[region] without checking for missing region mapping. This can produce opaque request errors instead of a clear configuration error.

Suggested fix
  var region = "default"
  if apiConfig.Region != nil && *apiConfig.Region != "" {
      region = *apiConfig.Region
  }
- url := fmt.Sprintf("%s/%s", q.BaseURL[region], q.URLSuffix.Chat)
+ baseURL := strings.TrimSuffix(q.BaseURL[region], "/")
+ if baseURL == "" {
+     return nil, fmt.Errorf("qiniu: no base URL configured for region %q", region)
+ }
+ url := fmt.Sprintf("%s/%s", baseURL, q.URLSuffix.Chat)
📝 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
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", q.BaseURL[region], q.URLSuffix.Chat)
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
baseURL := strings.TrimSuffix(q.BaseURL[region], "/")
if baseURL == "" {
return nil, fmt.Errorf("qiniu: no base URL configured for region %q", region)
}
url := fmt.Sprintf("%s/%s", baseURL, q.URLSuffix.Chat)
🤖 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/qiniu.go` around lines 144 - 149, The code builds url
:= fmt.Sprintf("%s/%s", q.BaseURL[region], q.URLSuffix.Chat) without verifying
that q.BaseURL has an entry for the computed region, which can cause opaque
runtime errors; update the ChatWithMessages flow to check that baseURL, e.g.
base, exists for the chosen region (lookup q.BaseURL[region] into a variable),
return a clear configuration error if missing, and only then build the URL using
base and q.URLSuffix.Chat (mirroring the validation already used for stream/list
paths).

Comment on lines +237 to +242
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
reasonContent, ok = messageMap["reasoning_content"].(string)
if !ok {
return nil, fmt.Errorf("invalid reasoning content format")
}

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

Don’t fail sync chat when reasoning_content is absent.

When thinking is enabled, the current parser returns an error if reasoning_content is missing or non-string, even if content is valid. That makes otherwise successful responses fail.

Suggested fix
  var reasonContent string
  if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
-     reasonContent, ok = messageMap["reasoning_content"].(string)
-     if !ok {
-         return nil, fmt.Errorf("invalid reasoning content format")
-     }
+     if raw, exists := messageMap["reasoning_content"]; exists {
+         if parsed, ok := raw.(string); ok {
+             reasonContent = parsed
+         }
+     }

      if reasonContent != "" && reasonContent[0] == '\n' {
          reasonContent = reasonContent[1:]
      }
  }
📝 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
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
reasonContent, ok = messageMap["reasoning_content"].(string)
if !ok {
return nil, fmt.Errorf("invalid reasoning content format")
}
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
if raw, exists := messageMap["reasoning_content"]; exists {
if parsed, ok := raw.(string); ok {
reasonContent = parsed
}
}
if reasonContent != "" && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}
🤖 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/qiniu.go` around lines 237 - 242, When parsing
messageMap in the code path guarded by chatModelConfig and
chatModelConfig.Thinking, do not return an error if "reasoning_content" is
absent or not a string; instead attempt to cast messageMap["reasoning_content"]
to string and if the cast fails set reasonContent = "" (or leave it nil/empty)
and continue processing so valid "content" does not cause the whole sync to
fail; update the block around reasonContent, messageMap,
chatModelConfig.Thinking to tolerate missing/invalid reasoning_content and only
use it when present and correctly typed.

Comment on lines +334 to +337
for scanner.Scan() {
line := scanner.Text()
common.Info(line)

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

Remove raw stream payload logging from info logs.

Line 336 logs full streamed content/reasoning chunks, which can leak sensitive user data and inflate logs in production.

Suggested fix
-        common.Info(line)
+        // Avoid logging raw SSE payloads (may contain user content / reasoning text).
📝 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
for scanner.Scan() {
line := scanner.Text()
common.Info(line)
for scanner.Scan() {
line := scanner.Text()
// Avoid logging raw SSE payloads (may contain user content / reasoning text).
🤖 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/qiniu.go` around lines 334 - 337, The loop that calls
scanner.Scan() currently logs the full payload via common.Info(line), which can
leak sensitive data and bloat logs; remove that raw logging and either delete
the common.Info(line) call or replace it with a non-sensitive log such as
common.Debug or common.Info that only records metadata (e.g., "stream chunk
received", length: len(line), or a safely truncated/redacted snippet) so the raw
contents of the variable line are never logged; update the scanner.Scan() loop
in qiniu.go (the block referencing variable line and common.Info) accordingly.

@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (187dc8a) to head (1d9944e).

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

@JinHai-CN
JinHai-CN merged commit 47626bb into infiniflow:main May 27, 2026
1 check passed
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.

2 participants