Skip to content

Go: implement provider: GPUStack (chat) - #15024

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
ai-mountain:feat/15023-gpustack-chat
May 21, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
ai-mountain:feat/15023-gpustack-chat

Conversation

@ai-mountain

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #15023

GPUStack is listed as unchecked in the Go-rewrite tracker #14736, and internal/service/llm.go:171 already classifies it as a self-deployed provider alongside Ollama, Xinference, LocalAI, and LM Studio — but internal/entity/models/ had no gpustack.go driver, so the new Go API server could not route GPUStack instances. This PR adds the chat surface for GPUStack so it lines up with the existing self-hosted Go drivers.

Changes

  • internal/entity/models/gpustack.go: new GPUStackModel implementing ChatWithMessages, ChatStreamlyWithSender, ListModels, and CheckConnection.
    • Chat at ${base}/v1/chat/completions, OpenAI-shape body, Authorization: Bearer <key>. The base URL is supplied by the tenant at instance creation time — no default, matching LM Studio / vLLM / Ollama / LocalAI / Xinference.
    • SSE stream parsing with the same shape as LongCat Go: implement provider: LongCat #14809: bumps the scanner buffer to 1 MB, rejects malformed data: frames, surfaces upstream {"error":...} frames mid-stream, and requires [DONE] or a finish_reason to declare the stream terminated.
    • ListModels hits ${base}/v1/models and parses the standard OpenAI catalog shape; CheckConnection delegates to it.
    • All other interface methods (Embed, Rerank, Balance, TranscribeAudio, AudioSpeech, OCRFile, ParseFile, ListTasks, ShowTask) return the no such method sentinel — Embed and Rerank will land as follow-on PRs, in line with how Novita, NVIDIA, and TogetherAI rolled out method-by-method.
  • conf/models/gpustack.json: new file with the chat and models URL suffixes (v1/chat/completions, v1/models); empty url and models so the tenant supplies them at instance creation time, matching the LM Studio JSON shape.
  • internal/entity/models/factory.go: route "gpustack" to NewGPUStackModel, alongside the other self-hosted providers.
  • internal/entity/models/gpustack_test.go: 20 unit tests covering chat happy-path, reasoning_content extraction, documented-field forwarding, all chat error paths (missing api key / model name / messages / base URL, HTTP error), stream happy-path, stream reasoning_content, stream=false guard, sender-required guard, terminal-frame guard, malformed-frame rejection, upstream-error surfacing, list-models happy-path with CheckConnection, list-models api-key guard, factory routing, Name(), and a sentinel check for the unsupported methods.

Type of change

  • New Feature (non-breaking change which adds functionality)

Notes for reviewers

@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: 702f3916-cb30-4592-a37f-87a54e659d1f

📥 Commits

Reviewing files that changed from the base of the PR and between c4e74be and b6350d3.

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

📝 Walkthrough

Walkthrough

Adds GPUStack as a new OpenAI‑compatible model provider: configuration, factory registration, a GPUStackModel driver with sync and SSE chat plus model listing, unsupported-method stubs, and a comprehensive test suite.

Changes

GPUStack Provider

Layer / File(s) Summary
Configuration & Factory Registration
conf/models/gpustack.json, internal/entity/models/factory.go, internal/entity/models/gpustack_test.go
Adds gpustack.json configuration defining chat and models endpoint routes with class: local, registers "gpustack" in the model factory's CreateModelDriver switch, and tests name identity and factory dispatch.
Driver Type & Test Infrastructure
internal/entity/models/gpustack.go, internal/entity/models/gpustack_test.go
Defines GPUStackModel type and constructor with region-aware base URL resolution and customized HTTP client pooling; adds HTTP and SSE test server helpers and a test-only constructor.
Chat Non-Streaming
internal/entity/models/gpustack.go, internal/entity/models/gpustack_test.go
Implements ChatWithMessages with input validation, non-stream JSON request building, response parsing including reasoning_content extraction; tests validate happy path, reasoning extraction, field forwarding, and client-side validation errors.
Chat Streaming with SSE
internal/entity/models/gpustack.go, internal/entity/models/gpustack_test.go
Implements ChatStreamlyWithSender with SSE streaming, delta event parsing and callback dispatch, enforced stream termination via [DONE] or finish_reason, and final end-of-stream marker; tests cover SSE assembly, reasoning extraction, stream truncation detection, and malformed frame rejection.
Model Listing & Connection Check
internal/entity/models/gpustack.go, internal/entity/models/gpustack_test.go
Implements ListModels (GET /v1/models) and CheckConnection delegating to it; tests verify authorization, model ID parsing, and API-key-required errors.
Unsupported Method Stubs
internal/entity/models/gpustack.go, internal/entity/models/gpustack_test.go
Adds explicit "no such method" error stubs for embeddings, reranking, balance, transcription, speech, OCR, parsing, and task APIs; tests verify error messages.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Application
  participant GPUDriver as GPUStackModel
  participant GPUAPI as GPUStack API
  participant Sender as Callback
  Client->>GPUDriver: ChatStreamlyWithSender(model, messages, apiConfig, sender)
  GPUDriver->>GPUDriver: Validate inputs (api key, model, messages), enforce stream:true
  GPUDriver->>GPUAPI: POST /v1/chat/completions (Accept: text/event-stream)
  GPUAPI-->>GPUDriver: SSE frames (data: {...})
  loop per SSE frame
    GPUDriver->>GPUDriver: Parse JSON, extract delta.content & delta.reasoning_content
    GPUDriver->>Sender: Invoke sender(content_ptr, reasoning_ptr)
  end
  GPUAPI-->>GPUDriver: data: [DONE] or finish_reason
  GPUDriver->>Sender: Send final end-of-stream marker
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

size:XL

Suggested reviewers

  • Haruko386

Poem

🐰 In code the GPUs hum and sing,

I stitched a chat and streaming wing,
Models listed, tests in place,
A tiny driver finds its race,
Hop, deploy — a joyful spring!

🚥 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 PR title clearly and specifically describes the main change: implementing GPUStack provider chat support in Go, which aligns with the primary objective of adding a new Go driver for GPUStack.
Description check ✅ Passed The PR description fully addresses the template by explaining the problem (#15023), detailing specific changes (gpustack.go, factory.go, gpustack.json, tests), and explicitly selecting 'New Feature' as the change type.
Linked Issues check ✅ Passed The PR implementation fully satisfies all coded objectives from #15023: GPUStackModel driver with ChatWithMessages and ChatStreamlyWithSender, ListModels, CheckConnection, tenant-supplied base URL, factory registration, and comprehensive unit tests matching stated requirements.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objective of implementing GPUStack chat support; no unrelated modifications such as Embed, Rerank, or other capabilities are included (deferred to follow-on PRs as documented).

✏️ 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

🤖 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/gpustack.go`:
- Around line 59-61: ChatStreamlyWithSender creates the streaming request with
context.Background() and can block forever; change it to use context.WithTimeout
like other calls (e.g., the pattern used in non-streaming functions) by deriving
a timed ctx, pass that ctx into http.NewRequestWithContext when creating the
request in ChatStreamlyWithSender, defer the cancel(), and ensure the
scanner/read loop checks ctx.Done() (or relies on request cancellation closing
the response body) so the loop exits if the timeout elapses; use the same
timeout duration constant or value used elsewhere in this file for consistency.
🪄 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: 64978d99-073d-496c-9380-22529a2d090a

📥 Commits

Reviewing files that changed from the base of the PR and between eacec86 and 68eb0e9.

📒 Files selected for processing (4)
  • conf/models/gpustack.json
  • internal/entity/models/factory.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/gpustack_test.go

Comment thread internal/entity/models/gpustack.go Resolved
@JinHai-CN
JinHai-CN requested a review from Haruko386 May 20, 2026 02:08

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

Hi @RenzoMXD, please do a small change

Comment thread conf/models/gpustack.json Resolved
@ai-mountain
ai-mountain requested a review from Haruko386 May 20, 2026 05:08

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

@RenzoMXD LGTM

@JinHai-CN

Copy link
Copy Markdown
Member

@RenzoMXD Since previous PR includes a binary file which is very big. So, I reset the head of main branch. Would you please re-submit the commit from current HEAD of main branch? Thank you very much.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 20, 2026

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

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

416-417: ⚡ Quick win

Add logging when session not found.

Per coding guidelines, new error flows should include logging. Other similar guard conditions in this file (e.g., lines 563–568, 578–584) log structured messages. Since the test docstring notes this condition can arise in multi-instance deployments, a log entry would aid production debugging.

Suggested addition
 def get_agent_session(agent_id, session_id, tenant_id):
     exists, conv = API4ConversationService.get_by_id(session_id)
     if not exists:
+        logging.info(
+            "get_agent_session miss: agent_id=%s session_id=%s tenant_id=%s",
+            agent_id,
+            session_id,
+            tenant_id,
+        )
         return get_data_error_result(message="Session not found!")
     return get_json_result(data=conv.to_dict())

As per coding guidelines, "Add logging for new flows" applies to **/*.py.

🤖 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 `@api/apps/restful_apis/agent_api.py` around lines 416 - 417, The guard
returning get_data_error_result when "exists" is false lacks a log entry; add a
structured error log before returning that records the missing session and
contextual identifiers (e.g., session_id, tenant_id or request_id when
available) using the same module logger used elsewhere (match the file's logger
like process_logger or logger) so the block referencing exists and
get_data_error_result emits a consistent diagnostic message for multi-instance
debugging.
🤖 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 `@Dockerfile`:
- Line 58: The Dockerfile pins NGINX via ARG NGINX_VERSION to 1.31.0-1~noble
which is a critical-security update; update the build workflow by either (a)
bumping ARG NGINX_VERSION to the latest patched version after you verify
compatibility with RAGFlow’s HTTP/2, rewrite, SCGI/uWSGI and charset usages, or
(b) if you cannot immediately upgrade, add a clear comment next to ARG
NGINX_VERSION documenting the security release (CVE-2026-42945 etc.), required
compatibility tests, and a TODO to perform those tests and upgrade before
production; ensure the change references the existing ARG NGINX_VERSION to keep
the Docker build consistent.

In `@test/unit_test/data_source/test_imap_connector_addr_parsing.py`:
- Around line 86-94: The test test_multi_address_header_warns_and_returns_first
uses caplog.records and incorrectly accesses rec.message (which doesn't exist);
update the assertion to use rec.getMessage() (e.g., check any("Multiple
addresses" in rec.getMessage() for rec in caplog.records)) or simplify by using
caplog.messages (e.g., any("Multiple addresses" in m for m in caplog.messages))
so the warning text is compared correctly; modify the code around
_parse_singular_addr call and the subsequent assertion to use one of these
alternatives.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 416-417: The guard returning get_data_error_result when "exists"
is false lacks a log entry; add a structured error log before returning that
records the missing session and contextual identifiers (e.g., session_id,
tenant_id or request_id when available) using the same module logger used
elsewhere (match the file's logger like process_logger or logger) so the block
referencing exists and get_data_error_result emits a consistent diagnostic
message for multi-instance debugging.
🪄 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: 5c0c4a61-a5fb-4741-91f9-f957d903bccf

📥 Commits

Reviewing files that changed from the base of the PR and between 6dec677 and f14f17a.

📒 Files selected for processing (7)
  • Dockerfile
  • api/apps/restful_apis/agent_api.py
  • common/data_source/imap_connector.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • test/unit_test/api/apps/restful_apis/test_get_agent_session.py
  • test/unit_test/data_source/test_imap_connector_addr_parsing.py

Comment thread Dockerfile Resolved
@ai-mountain
ai-mountain force-pushed the feat/15023-gpustack-chat branch from f14f17a to c4e74be Compare May 20, 2026 12:25
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 20, 2026

@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

♻️ Duplicate comments (1)
internal/entity/models/gpustack.go (1)

265-277: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Bound the streaming request lifetime.

Line 265 builds the SSE request from context.Background() while the shared http.Client has no overall Timeout, so once headers are in, a stalled upstream can block the scanner loop forever and pin the request goroutine. Please give the streaming call its own deadline or cancellation path instead of relying only on ResponseHeaderTimeout.

This verification should show ResponseHeaderTimeout on the transport, no http.Client.Timeout, and ChatStreamlyWithSender creating the request from context.Background().

Based on learnings: when httpClient.Timeout is intentionally unset, a per-request context.WithTimeout is the legitimate overall deadline.

#!/bin/bash
set -euo pipefail

sed -n '48,61p' internal/entity/models/gpustack.go
sed -n '260,277p' internal/entity/models/gpustack.go
rg -n -C2 'nonStreamCallTimeout|NewRequestWithContext\(context\.Background\(\)|ResponseHeaderTimeout|httpClient:\s*&http\.Client' internal/entity/models/gpustack.go
🤖 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/gpustack.go` around lines 265 - 277, The streaming
request is created with http.NewRequestWithContext(context.Background()) which
can hang indefinitely because g.httpClient has no overall Timeout; modify
ChatStreamlyWithSender to create the request with a cancellable per-request
context (e.g., ctx, cancel := context.WithTimeout(parentCtx, streamDeadline) or
context.WithCancel(parentCtx) and defer cancel()) and use
http.NewRequestWithContext(ctx, ...) instead of context.Background(); ensure the
cancel is invoked on exit or on caller cancellation so the g.httpClient.Do(req)
goroutine cannot be pinned while ResponseHeaderTimeout remains the only
transport safeguard.
🤖 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/gpustack_test.go`:
- Around line 152-156: The test dereferences resp.Answer and resp.ReasonContent
directly which can panic if they are nil; update the assertions in
gpustack_test.go to guard against nil first (e.g., check resp != nil and
t.Fatalf or t.Errorf if resp.Answer or resp.ReasonContent is nil) and only then
compare their values ("12" and "0.15 * 80 = 12"); alternatively extract safe
helper checks or use conditional comparisons that handle nil to produce clean
test failures referencing resp.Answer and resp.ReasonContent.

---

Duplicate comments:
In `@internal/entity/models/gpustack.go`:
- Around line 265-277: The streaming request is created with
http.NewRequestWithContext(context.Background()) which can hang indefinitely
because g.httpClient has no overall Timeout; modify ChatStreamlyWithSender to
create the request with a cancellable per-request context (e.g., ctx, cancel :=
context.WithTimeout(parentCtx, streamDeadline) or context.WithCancel(parentCtx)
and defer cancel()) and use http.NewRequestWithContext(ctx, ...) instead of
context.Background(); ensure the cancel is invoked on exit or on caller
cancellation so the g.httpClient.Do(req) goroutine cannot be pinned while
ResponseHeaderTimeout remains the only transport safeguard.
🪄 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: cd0f9d53-6b34-4c47-afac-9b1e542e3488

📥 Commits

Reviewing files that changed from the base of the PR and between f14f17a and c4e74be.

📒 Files selected for processing (4)
  • conf/models/gpustack.json
  • internal/entity/models/factory.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/gpustack_test.go
✅ Files skipped from review due to trivial changes (1)
  • conf/models/gpustack.json

Comment on lines +152 to +156
if *resp.Answer != "12" {
t.Errorf("Answer=%q", *resp.Answer)
}
if *resp.ReasonContent != "0.15 * 80 = 12" {
t.Errorf("ReasonContent=%q", *resp.ReasonContent)

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

Guard nil before dereferencing response pointers in assertions.

resp.Answer and resp.ReasonContent are dereferenced directly here; if either is nil, the test panics instead of reporting a clean assertion failure.

Suggested fix
-	if *resp.Answer != "12" {
-		t.Errorf("Answer=%q", *resp.Answer)
-	}
-	if *resp.ReasonContent != "0.15 * 80 = 12" {
-		t.Errorf("ReasonContent=%q", *resp.ReasonContent)
-	}
+	if resp.Answer == nil || *resp.Answer != "12" {
+		t.Errorf("Answer=%v", resp.Answer)
+	}
+	if resp.ReasonContent == nil || *resp.ReasonContent != "0.15 * 80 = 12" {
+		t.Errorf("ReasonContent=%v", resp.ReasonContent)
+	}
📝 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
if *resp.Answer != "12" {
t.Errorf("Answer=%q", *resp.Answer)
}
if *resp.ReasonContent != "0.15 * 80 = 12" {
t.Errorf("ReasonContent=%q", *resp.ReasonContent)
if resp.Answer == nil || *resp.Answer != "12" {
t.Errorf("Answer=%v", resp.Answer)
}
if resp.ReasonContent == nil || *resp.ReasonContent != "0.15 * 80 = 12" {
t.Errorf("ReasonContent=%v", resp.ReasonContent)
}
🤖 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/gpustack_test.go` around lines 152 - 156, The test
dereferences resp.Answer and resp.ReasonContent directly which can panic if they
are nil; update the assertions in gpustack_test.go to guard against nil first
(e.g., check resp != nil and t.Fatalf or t.Errorf if resp.Answer or
resp.ReasonContent is nil) and only then compare their values ("12" and "0.15 *
80 = 12"); alternatively extract safe helper checks or use conditional
comparisons that handle nil to produce clean test failures referencing
resp.Answer and resp.ReasonContent.

@JinHai-CN JinHai-CN added the ci Continue Integration label May 20, 2026
@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (dc01e0e) to head (b6350d3).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15024      +/-   ##
==========================================
- Coverage   94.53%   93.12%   -1.41%     
==========================================
  Files          10       10              
  Lines         713      713              
  Branches      116      116              
==========================================
- Hits          674      664      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ 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 c7ac9b7 into infiniflow:main May 21, 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: GPUStack in Go driver

3 participants