Repository navigation
feat[go]: implement provider: TokenHub - #15159
Conversation
📝 WalkthroughWalkthroughA new TokenHub provider is added to the RAGFlow system. The PR introduces a JSON configuration file defining the TokenHub API endpoints and model catalog, plus a complete Go driver ( ChangesTokenHub Provider Integration
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes 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: 5
🤖 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/tokenhub.go`:
- Around line 421-424: ListModels currently dereferences apiConfig and
apiConfig.ApiKey and performs unchecked type assertions that can panic; update
TokenHubModel.ListModels to first nil-check apiConfig and its ApiKey (return a
clear error if nil/empty), validate region safely before dereferencing, and
replace raw type assertions in the response-parsing code (the block around the
current unchecked assertions at lines referenced) with guarded type checks (use
ok-style assertions and handle unexpected types by returning an error). Ensure
all early returns provide descriptive errors rather than allowing a panic.
- Line 253: Replace the raw logging call common.Info(line) that writes every SSE
line to logs with a safe alternative: stop logging full streamed model output
and instead log only non-sensitive metadata (e.g., event type, truncated length,
or a hashed/truncated fingerprint). Locate the occurrence of common.Info(line)
in tokenhub.go (the SSE/stream handling code) and either remove the call or
replace it with a redaction-aware helper that strips or hashes content before
logging (e.g., logSummary(eventType, len, hashPrefix)). Ensure no user prompt or
model text is written to logs.
- Around line 335-336: In the Embed function validate required pointers before
dereferencing: check that modelName != nil (and non-empty if applicable) before
using *modelName, and check apiConfig != nil and apiConfig.ApiKey != nil (and
non-empty) before using *apiConfig.ApiKey; if any are missing return a clear
error instead of proceeding. Also validate inputs like texts as needed and
update the blocks that build the request payload (references: Embed, modelName,
apiConfig, apiConfig.ApiKey, texts) to use the validated values.
- Around line 235-237: The code dereferences *apiConfig.ApiKey when setting the
Authorization header (req.Header.Set with fmt.Sprintf), which can panic if
apiConfig or apiConfig.ApiKey is nil; update the surrounding function to first
validate that apiConfig != nil and apiConfig.ApiKey != nil (or non-empty) and
handle the error path (return an error or skip setting the header) before
calling fmt.Sprintf; reference the apiConfig and ApiKey fields and the
req.Header.Set call so the nil-checks are added immediately prior to that header
assignment.
- Around line 74-77: The ChatWithMessages path currently copies
chatModelConfig.Stream into reqBody (reqBody["stream"] =
*chatModelConfig.Stream) which can enable SSE streaming for a non-streaming
function and break JSON parsing; update the ChatWithMessages implementation to
refuse or override streaming by checking chatModelConfig.Stream before setting
reqBody: if chatModelConfig.Stream != nil and *chatModelConfig.Stream is true,
either return an error or set reqBody["stream"] = false/unset it so the request
is always non-streaming; make this change around the code that sets
reqBody["stream"] (referencing chatModelConfig.Stream and reqBody) so upstream
SSE chunks are never enabled for ChatWithMessages.
🪄 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: bb188444-77be-48ba-adfa-ff121a74ff9e
📒 Files selected for processing (2)
conf/models/tokenhub.jsoninternal/entity/models/tokenhub.go
| if chatModelConfig != nil { | ||
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Do not allow streaming mode in ChatWithMessages.
Line 76 allows stream=true in a non-streaming method, but Lines 126-150 always parse a full JSON response. This can break parsing when upstream returns SSE chunks.
Proposed fix
- if chatModelConfig.Stream != nil {
- reqBody["stream"] = *chatModelConfig.Stream
- }
+ // Keep non-streaming behavior for ChatWithMessages.
+ reqBody["stream"] = false📝 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 chatModelConfig != nil { | |
| if chatModelConfig.Stream != nil { | |
| reqBody["stream"] = *chatModelConfig.Stream | |
| } | |
| // Keep non-streaming behavior for ChatWithMessages. | |
| reqBody["stream"] = false | |
| if chatModelConfig != nil { |
🤖 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/tokenhub.go` around lines 74 - 77, The
ChatWithMessages path currently copies chatModelConfig.Stream into reqBody
(reqBody["stream"] = *chatModelConfig.Stream) which can enable SSE streaming for
a non-streaming function and break JSON parsing; update the ChatWithMessages
implementation to refuse or override streaming by checking
chatModelConfig.Stream before setting reqBody: if chatModelConfig.Stream != nil
and *chatModelConfig.Stream is true, either return an error or set
reqBody["stream"] = false/unset it so the request is always non-streaming; make
this change around the code that sets reqBody["stream"] (referencing
chatModelConfig.Stream and reqBody) so upstream SSE chunks are never enabled for
ChatWithMessages.
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
There was a problem hiding this comment.
Guard apiConfig and apiConfig.ApiKey before dereference.
Line 236 dereferences *apiConfig.ApiKey without nil checks, which can panic on invalid input.
Proposed fix
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return fmt.Errorf("api key is required")
+ }
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))🤖 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/tokenhub.go` around lines 235 - 237, The code
dereferences *apiConfig.ApiKey when setting the Authorization header
(req.Header.Set with fmt.Sprintf), which can panic if apiConfig or
apiConfig.ApiKey is nil; update the surrounding function to first validate that
apiConfig != nil and apiConfig.ApiKey != nil (or non-empty) and handle the error
path (return an error or skip setting the header) before calling fmt.Sprintf;
reference the apiConfig and ApiKey fields and the req.Header.Set call so the
nil-checks are added immediately prior to that header assignment.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) |
There was a problem hiding this comment.
Avoid logging raw streamed model output.
Line 253 logs every SSE line, which can leak user prompts/model outputs into logs.
Proposed fix
- common.Info(line)
+ // Avoid logging raw model stream payloads (may contain sensitive content).📝 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.
| common.Info(line) | |
| // Avoid logging raw model stream payloads (may contain sensitive content). |
🤖 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/tokenhub.go` at line 253, Replace the raw logging call
common.Info(line) that writes every SSE line to logs with a safe alternative:
stop logging full streamed model output and instead log only non-sensitive
metadata (e.g., event type, truncated length, or a hashed/truncated
fingerprint). Locate the occurrence of common.Info(line) in tokenhub.go (the
SSE/stream handling code) and either remove the call or replace it with a
redaction-aware helper that strips or hashes content before logging (e.g.,
logSummary(eventType, len, hashPrefix)). Ensure no user prompt or model text is
written to logs.
| "model": *modelName, | ||
| "input": texts, |
There was a problem hiding this comment.
Validate required pointers in Embed before use.
Line 335 dereferences modelName, and Line 350 dereferences apiConfig.ApiKey without validation. Both are panic paths.
Proposed fix
func (t *TokenHubModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
if len(texts) == 0 {
return []EmbeddingData{}, nil
}
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }Also applies to: 349-350
🤖 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/tokenhub.go` around lines 335 - 336, In the Embed
function validate required pointers before dereferencing: check that modelName
!= nil (and non-empty if applicable) before using *modelName, and check
apiConfig != nil and apiConfig.ApiKey != nil (and non-empty) before using
*apiConfig.ApiKey; if any are missing return a clear error instead of
proceeding. Also validate inputs like texts as needed and update the blocks that
build the request payload (references: Embed, modelName, apiConfig,
apiConfig.ApiKey, texts) to use the validated values.
| func (t *TokenHubModel) ListModels(apiConfig *APIConfig) ([]string, error) { | ||
| var region = "default" | ||
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region |
There was a problem hiding this comment.
Harden ListModels against nil inputs and malformed responses.
Line 423 assumes apiConfig is non-nil, Line 443 assumes ApiKey is non-nil, and Lines 468-470 use unchecked type assertions. Any mismatch can panic the process.
Proposed fix
func (t *TokenHubModel) ListModels(apiConfig *APIConfig) ([]string, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
@@
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
- models = append(models, modelName)
- }
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models response format")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ modelName, ok := modelMap["id"].(string)
+ if !ok || modelName == "" {
+ continue
+ }
+ models = append(models, modelName)
+ }Also applies to: 443-443, 468-470
🤖 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/tokenhub.go` around lines 421 - 424, ListModels
currently dereferences apiConfig and apiConfig.ApiKey and performs unchecked
type assertions that can panic; update TokenHubModel.ListModels to first
nil-check apiConfig and its ApiKey (return a clear error if nil/empty), validate
region safely before dereferencing, and replace raw type assertions in the
response-parsing code (the block around the current unchecked assertions at
lines referenced) with guarded type checks (use ok-style assertions and handle
unexpected types by returning an error). Ensure all early returns provide
descriptive errors rather than allowing a panic.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15159 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
Haruko386
left a comment
There was a problem hiding this comment.
Hi @Dimon0000000, LGTM
Thank you for your contribution : )
## Summary - Wire the Go TokenHub provider through the model factory. - Harden TokenHub request handling for chat, streaming, embeddings, and model listing. - Add focused TokenHub unit coverage for factory wiring and provider behavior. ## Notes - Refs #14736. - Follows up #15159. Co-authored-by: Jin Hai <[email protected]>
What problem does this PR solve?
implement provider TokenHub
Type of change