Repository navigation
Go: implement provider: GPUStack (chat) - #15024
Conversation
|
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds 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. ChangesGPUStack Provider
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
conf/models/gpustack.jsoninternal/entity/models/factory.gointernal/entity/models/gpustack.gointernal/entity/models/gpustack_test.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @RenzoMXD, please do a small change
|
@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. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)
416-417: ⚡ Quick winAdd 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
📒 Files selected for processing (7)
Dockerfileapi/apps/restful_apis/agent_api.pycommon/data_source/imap_connector.pyrag/llm/chat_model.pyrag/llm/cv_model.pytest/unit_test/api/apps/restful_apis/test_get_agent_session.pytest/unit_test/data_source/test_imap_connector_addr_parsing.py
f14f17a to
c4e74be
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
internal/entity/models/gpustack.go (1)
265-277:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winBound the streaming request lifetime.
Line 265 builds the SSE request from
context.Background()while the sharedhttp.Clienthas no overallTimeout, 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 onResponseHeaderTimeout.This verification should show
ResponseHeaderTimeouton the transport, nohttp.Client.Timeout, andChatStreamlyWithSendercreating the request fromcontext.Background().Based on learnings: when
httpClient.Timeoutis intentionally unset, a per-requestcontext.WithTimeoutis 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
📒 Files selected for processing (4)
conf/models/gpustack.jsoninternal/entity/models/factory.gointernal/entity/models/gpustack.gointernal/entity/models/gpustack_test.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/gpustack.json
| if *resp.Answer != "12" { | ||
| t.Errorf("Answer=%q", *resp.Answer) | ||
| } | ||
| if *resp.ReasonContent != "0.15 * 80 = 12" { | ||
| t.Errorf("ReasonContent=%q", *resp.ReasonContent) |
There was a problem hiding this comment.
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.
| 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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Fixes #15023
GPUStack is listed as unchecked in the Go-rewrite tracker #14736, and
internal/service/llm.go:171already classifies it as a self-deployed provider alongside Ollama, Xinference, LocalAI, and LM Studio — butinternal/entity/models/had nogpustack.godriver, 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: newGPUStackModelimplementingChatWithMessages,ChatStreamlyWithSender,ListModels, andCheckConnection.${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.data:frames, surfaces upstream{"error":...}frames mid-stream, and requires[DONE]or afinish_reasonto declare the stream terminated.ListModelshits${base}/v1/modelsand parses the standard OpenAI catalog shape;CheckConnectiondelegates to it.Embed,Rerank,Balance,TranscribeAudio,AudioSpeech,OCRFile,ParseFile,ListTasks,ShowTask) return theno such methodsentinel — 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 thechatandmodelsURL suffixes (v1/chat/completions,v1/models); emptyurlandmodelsso the tenant supplies them at instance creation time, matching the LM Studio JSON shape.internal/entity/models/factory.go: route"gpustack"toNewGPUStackModel, 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=falseguard, sender-required guard, terminal-frame guard, malformed-frame rejection, upstream-error surfacing, list-models happy-path withCheckConnection, list-models api-key guard, factory routing,Name(), and a sentinel check for the unsupported methods.Type of change
Notes for reviewers
rag/llm/chat_model.py:1872(LiteLLMopenai/route tourljoin(base_url, "v1")).