Skip to content

feat[go]: implement provider: TokenHub - #15159

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Dimon0000000:main
May 25, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Dimon0000000:main

Conversation

@Dimon0000000

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

implement provider TokenHub

Type of change

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

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

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A 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 (TokenHubModel) implementing chat (streaming and non-streaming), embeddings, model discovery, connection validation, and stub methods for unsupported features like ASR, TTS, and OCR.

Changes

TokenHub Provider Integration

Layer / File(s) Summary
TokenHub Configuration
conf/models/tokenhub.json
Provider base URL, endpoint paths for chat, models, and embeddings, and model catalog for 7 models (GPT-4o, Claude, Gemini) with token limits, capability flags, and Gemini thinking mode settings.
TokenHubModel Type and Initialization
internal/entity/models/tokenhub.go (lines 1–39)
TokenHubModel struct with BaseURL, URLSuffix, and internal http.Client; NewTokenHubModel constructor and NewInstance factory for region-specific instances.
Chat Operations
internal/entity/models/tokenhub.go (lines 45–320)
ChatWithMessages for non-streaming chat with message validation, parameter override, and response parsing; ChatStreamlyWithSender for streaming chat with SSE event parsing, delta forwarding, and [DONE] termination.
Embeddings and Model Discovery
internal/entity/models/tokenhub.go (lines 322–475)
Embed to post texts and parse data[] embedding vectors; ListModels to retrieve available model identifiers from API response.
Connection Check and Stubs
internal/entity/models/tokenhub.go (lines 393–492)
CheckConnection delegating to ListModels, Balance as stub, and unsupported method stubs (Rerank, ASR, TTS, OCR, file parsing, task listing) returning "no such method" errors.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested reviewers

  • tmimmanuel

Poem

A new provider hops into view,
TokenHub chat and embeddings too,
Streaming responses flow like a stream,
Models and discovery fulfill the dream! 🐰✨

🚥 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 title clearly identifies the main change as implementing a TokenHub provider in Go, which directly matches the PR's core objective.
Description check ✅ Passed The description includes the required template sections (problem statement and type of change), though the problem statement is minimal and lacks background context.
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.

@Haruko386 Haruko386 added the ci Continue Integration label May 22, 2026
@Dimon0000000
Dimon0000000 marked this pull request as draft May 22, 2026 11:23
@Dimon0000000
Dimon0000000 marked this pull request as ready for review May 22, 2026 11:23

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

📥 Commits

Reviewing files that changed from the base of the PR and between 302f97d and 25c6d70.

📒 Files selected for processing (2)
  • conf/models/tokenhub.json
  • internal/entity/models/tokenhub.go

Comment on lines +74 to +77
if chatModelConfig != nil {
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

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

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.

Suggested change
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.

Comment on lines +235 to +237
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

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 | 🔴 Critical | ⚡ Quick win

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)

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

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.

Suggested change
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.

Comment on lines +335 to +336
"model": *modelName,
"input": texts,

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 | 🔴 Critical | ⚡ Quick win

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.

Comment on lines +421 to +424
func (t *TokenHubModel) ListModels(apiConfig *APIConfig) ([]string, error) {
var region = "default"
if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region

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 | 🔴 Critical | ⚡ Quick win

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

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (302f97d) to head (25c6d70).

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

@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 @Dimon0000000, LGTM
Thank you for your contribution : )

@JinHai-CN
JinHai-CN merged commit bb6cfc1 into infiniflow:main May 25, 2026
1 check passed
JinHai-CN added a commit that referenced this pull request May 26, 2026
## 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]>
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.

3 participants