Skip to content

Go: implement provider: ModelScope - #15041

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
dripsmvcp:fix/15040-go-modelscope-driver
May 26, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
dripsmvcp:fix/15040-go-modelscope-driver

Conversation

@dripsmvcp

@dripsmvcp dripsmvcp commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #15040.

ModelScope was listed unchecked in the Go-rewrite tracker #14736 and already had an llm_factories.json entry (tags: LLM) but no Go driver, so the new Go API server could not route ModelScope instances. The Python side has supported it through the OpenAI-compatible base at rag/llm/chat_model.py:618 (ModelScopeChat), which requires a user-supplied base URL and appends /v1.

This adds:

  • internal/entity/models/modelscope.go: self-hosted OpenAI-compatible driver with chat (sync + SSE stream with idle-timeout cancellation), list_models, and check_connection. Auth header is optional, matching the xinference pattern, so deployments without auth and auth-enabled deployments both work. Base URL is normalized so users can configure either the root endpoint or the /v1 endpoint.
  • internal/entity/models/modelscope_test.go: 12 tests covering name, URL normalization, factory routing, chat happy path / auth header / reasoning_content extraction, stream happy path / stream=false rejection / idle cancellation, list_models + check_connection, missing-base-URL clear error, and the no-such-method sentinels.
  • conf/models/modelscope.json: shipped config (class: "local", url_suffix v1/chat/completions and v1/models).
  • internal/entity/models/factory.go: case "modelscope" → ModelScopeModel.
  • internal/service/llm.go: ModelScope added to the selfDeployed map alongside Ollama, Xinference, LocalAI, LM-Studio, GPUStack — the Python side requires user-supplied URL with no default, so the Go side classifies it the same way.

Follow-on issues will add Embed and Rerank, in line with how Novita, NVIDIA, TogetherAI, and other providers landed method-by-method.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 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

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: e749fa02-24f6-49e3-af29-7057bb0cf444

📥 Commits

Reviewing files that changed from the base of the PR and between fbc52f7 and 3994eb2.

📒 Files selected for processing (1)
  • internal/entity/models/factory.go

📝 Walkthrough

Walkthrough

Adds ModelScope provider config and factory registration, implements a new ModelScopeModel driver with non-streaming and SSE-streaming chat, model listing and connection check, unsupported-method stubs, unit tests, and marks ModelScope as self-deployed.

Changes

ModelScope provider

Layer / File(s) Summary
Configuration and factory routing
conf/models/modelscope.json, internal/entity/models/factory.go
Adds modelscope config (chat → v1/chat/completions, models → v1/models) and registers "modelscope" in CreateModelDriver.
Driver type, constructor, and init helpers
internal/entity/models/modelscope.go
Adds ModelScopeModel, request/response structs, constructor, NewInstance, Name, HTTP client, and base-URL normalization.
Auth, region, reasoning helpers
internal/entity/models/modelscope.go
Bearer auth injection, region selection, and reasoning extraction helpers (including SSE delta handling).
Request builder and params
internal/entity/models/modelscope.go
Converts internal messages and ChatConfig into OpenAI-compatible chat JSON (model, stream, max_tokens, temperature, top_p, stop).
Non-streaming chat
internal/entity/models/modelscope.go
ChatWithMessages posts JSON with timeout, validates response, and returns ChatResponse (Answer + ReasonContent).
Streaming chat
internal/entity/models/modelscope.go
ChatStreamlyWithSender posts stream:true, parses SSE data: events, emits content/reasoning deltas to a callback, enforces idle timeout, and requires terminal marker.
Model listing, balance, connection, and stubs
internal/entity/models/modelscope.go
ListModels GET /v1/models and returns non-empty ids; CheckConnection delegates to ListModels; Balance and task endpoints stubbed; unsupported methods return "no such method".
Service registration
internal/service/llm.go
Adds ModelScope to selfDeployed map so matching models are treated as self-hosted/available.
Test suite
internal/entity/models/modelscope_test.go
Tests for Name, factory routing, base-URL normalization, chat (with/without auth), reasoning extraction, streaming SSE behavior and idle timeout, model listing, check connection, missing-base errors, and unsupported-method stubs.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ModelScopeModel
  participant HTTPClient
  participant ModelScopeAPI
  Client->>ModelScopeModel: ChatWithMessages / ChatStreamlyWithSender
  ModelScopeModel->>ModelScopeModel: normalizeModelScopeBaseURL
  ModelScopeModel->>ModelScopeModel: setModelScopeAuth (if API key)
  ModelScopeModel->>ModelScopeModel: buildModelScopeChatBody
  ModelScopeModel->>HTTPClient: POST /v1/chat/completions (stream flag)
  HTTPClient->>ModelScopeAPI: JSON request
  alt Non-Streaming
    ModelScopeAPI-->>HTTPClient: 200 OK with choice[0]
    HTTPClient-->>ModelScopeModel: response body
    ModelScopeModel->>Client: ChatResponse (Answer + ReasonContent)
  else Streaming
    ModelScopeAPI-->>HTTPClient: 200 OK + SSE stream
    loop per data: event
      HTTPClient-->>ModelScopeModel: data: JSON delta
      ModelScopeModel->>Client: callback with content/reasoning delta
    end
    ModelScopeModel-->>Client: complete on [DONE] or finish_reason
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped to a ModelScope door,
Streams of tokens whispered more,
SSE drifts and answers bloom,
Tests keep watch and chase the gloom,
A rabbit cheers the provider's lore.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.76% 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 "Go: implement provider: ModelScope" accurately summarizes the main change—adding a Go driver implementation for the ModelScope provider.
Description check ✅ Passed The PR description is comprehensive and addresses all template sections: clearly states the problem (missing Go driver for ModelScope), identifies it as a New Feature, details implementation across all modified files, and provides relevant context.
Linked Issues check ✅ Passed The PR fully addresses all objectives from issue #15040: implements ModelScopeModel with chat (sync + streaming), list_models, check_connection, normalizes base URLs, makes auth optional, registers in factory and selfDeployed map, and appropriately defers Embed/Rerank to follow-on issues.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the ModelScope provider: the driver implementation, tests, config file, factory registration, and selfDeployed map addition—no extraneous modifications detected.

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


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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/entity/models/modelscope_test.go (1)

177-178: 💤 Low value

Consider checking errors for better test diagnostics.

The handler silently ignores errors from io.ReadAll and json.Unmarshal. While unlikely to fail in this simple test, explicitly checking and logging errors would make debugging easier if something unexpected happens.

Optional improvement
-		raw, _ := io.ReadAll(r.Body)
-		_ = json.Unmarshal(raw, &seen)
+		raw, err := io.ReadAll(r.Body)
+		if err != nil {
+			t.Errorf("read body: %v", err)
+			http.Error(w, "read error", http.StatusBadRequest)
+			return
+		}
+		if err := json.Unmarshal(raw, &seen); err != nil {
+			t.Errorf("unmarshal request: %v", err)
+			http.Error(w, "unmarshal error", http.StatusBadRequest)
+			return
+		}
🤖 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/modelscope_test.go` around lines 177 - 178, The test
currently ignores errors from io.ReadAll and json.Unmarshal which can obscure
failures; update the test in modelscope_test.go to check and fail on those
errors (e.g., capture err := io.ReadAll(r.Body) and if err != nil call t.Fatalf
or use require.NoError) and likewise check the error returned by json.Unmarshal
when decoding into seen so failures surface immediately; locate the
read/unmarshal calls around io.ReadAll and json.Unmarshal and replace the
ignored-error pattern with explicit error handling.
🤖 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/modelscope_test.go`:
- Around line 91-99: The test HTTP handler currently logs failures when reading
the request body or unmarshalling JSON (the io.ReadAll(r.Body) and
json.Unmarshal(raw, &seen) paths using raw, err, seen and t.Errorf) but returns
without writing an HTTP response; update the handler so after calling t.Errorf
you also write an appropriate HTTP error response (e.g., call w.WriteHeader with
a 400/500 status and write a short error message) for both the read and
unmarshal error branches so the client won't hang and tests get a proper HTTP
failure response.

---

Nitpick comments:
In `@internal/entity/models/modelscope_test.go`:
- Around line 177-178: The test currently ignores errors from io.ReadAll and
json.Unmarshal which can obscure failures; update the test in modelscope_test.go
to check and fail on those errors (e.g., capture err := io.ReadAll(r.Body) and
if err != nil call t.Fatalf or use require.NoError) and likewise check the error
returned by json.Unmarshal when decoding into seen so failures surface
immediately; locate the read/unmarshal calls around io.ReadAll and
json.Unmarshal and replace the ignored-error pattern with explicit error
handling.
🪄 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: a1133c44-2bf5-40fa-98ee-819cb87bc4b0

📥 Commits

Reviewing files that changed from the base of the PR and between 2836a93 and f0a3c14.

📒 Files selected for processing (5)
  • conf/models/modelscope.json
  • internal/entity/models/factory.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/modelscope_test.go
  • internal/service/llm.go

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

@dripsmvcp LGTM

dripsmvcp added 2 commits May 21, 2026 17:39
Closes infiniflow#15040.

ModelScope was listed unchecked in the Go-rewrite tracker infiniflow#14736 and
already had an llm_factories.json entry (tags: LLM) but no Go driver,
so the new Go API server could not route ModelScope instances. The
Python side has supported it through the OpenAI-compatible base at
rag/llm/chat_model.py:618 (ModelScopeChat), which requires a
user-supplied base URL and appends /v1.

This adds:
- internal/entity/models/modelscope.go: self-hosted OpenAI-compatible
  driver with chat (sync + SSE stream with idle-timeout cancellation),
  list_models, and check_connection. Auth header is optional, matching
  the xinference pattern, so deployments without auth and auth-enabled
  deployments both work. Base URL is normalized so users can configure
  either the root endpoint or the /v1 endpoint.
- internal/entity/models/modelscope_test.go: 12 tests covering name,
  URL normalization, factory routing, chat happy path / auth header /
  reasoning_content extraction, stream happy path / stream=false
  rejection / idle cancellation, list_models + check_connection,
  missing-base-URL clear error, and the no-such-method sentinels.
- conf/models/modelscope.json: shipped config (class: "local",
  url_suffix v1/chat/completions and v1/models).
- internal/entity/models/factory.go: case "modelscope" → ModelScopeModel.
- internal/service/llm.go: ModelScope added to the selfDeployed map
  alongside Ollama, Xinference, LocalAI, LM-Studio, GPUStack — the
  Python side requires user-supplied URL with no default, so the Go
  side classifies it the same way.

Follow-on issues will add Embed and Rerank, in line with how Novita,
NVIDIA, TogetherAI, and other providers landed method-by-method.
@dripsmvcp
dripsmvcp force-pushed the fix/15040-go-modelscope-driver branch from 895febe to fbc52f7 Compare May 21, 2026 08:40
@Haruko386 Haruko386 added the ci Continue Integration label May 26, 2026
@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.12%. Comparing base (c3b38d3) to head (3994eb2).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15041   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  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 a48bcf8 into infiniflow:main May 26, 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement provider: ModelScope in Go driver

3 participants