Skip to content

fix(tokenhub): wire Go driver and harden requests - #15224

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
JSONbored:codex/tokenhub-driver-wiring
May 26, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
JSONbored:codex/tokenhub-driver-wiring

Conversation

@JSONbored

Copy link
Copy Markdown
Contributor

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.

What changed

  • Register tokenhub in ModelFactory so configured TokenHub instances create TokenHubModel instead of falling through to the dummy driver.
  • Keep ChatWithMessages on the non-streaming path even when a shared chat config contains stream: true.
  • Validate required API key, model, and sender inputs before sending TokenHub requests.
  • Remove raw SSE line logging from streaming responses.
  • Guard TokenHub model-list response parsing against malformed rows or unexpected response shapes.

Why

TokenHub provider configuration and the driver were added in #15159, but the factory path still did not instantiate the TokenHub driver. This completes that wiring and adds regression coverage for the Go provider work tracked under #14736.

Validation

  • go test ./internal/entity/models -run TestTokenHub -count=1 -v
  • git diff --check
  • CodeRabbit review on the uncommitted diff; follow-up test coverage was added and the final review reported no findings.
  • Codex Security diff review found no new issues in the TokenHub changes.

Notes

@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: bbb8f1f9-dec3-4d12-882e-8780483ef484

📥 Commits

Reviewing files that changed from the base of the PR and between e2637ea and ddc6f80.

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

📝 Walkthrough

Walkthrough

This PR registers TokenHub in the model factory, tightens input validation and defensive parsing in the TokenHub model (chat, streaming, embed, list), removes per-line SSE logging, and adds a comprehensive HTTP/SSE test suite covering these behaviors.

Changes

TokenHub Provider Registration and Implementation

Layer / File(s) Summary
Factory Registration
internal/entity/models/factory.go
CreateModelDriver now recognizes the "tokenhub" provider (case-insensitive) and returns a NewTokenHubModel instance.
Implementation Hardening
internal/entity/models/tokenhub.go
Import cleanup; stricter input validation requiring non-empty API key in ChatWithMessages, ChatStreamlyWithSender, Embed, and ListModels; chat requests forced non-streaming; streaming API enforces Stream config when provided; removed per-line SSE logging; defensive ListModels response parsing validating data shape before extracting model ids.
Comprehensive Test Coverage
internal/entity/models/tokenhub_test.go
HTTP and SSE test helpers; factory instantiation test; chat tests (non-streaming, API key required); streaming tests (happy path, stream config enforcement, sender required, API key required); embedding tests (happy path and input/api-key validation); model listing tests (skip malformed items, response shape and API key validation).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

🐞 bug

Suggested reviewers

  • Haruko386

Poem

🐰 A token tucked beneath my paw, so neat,
I guard each key and streaming beat,
I skip the noise, parse shapes with care,
And test the paths I helped prepare —
Hoppity checks and code complete.

🚥 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 and specifically summarizes the main changes: wiring the TokenHub Go driver and hardening requests.
Description check ✅ Passed The description provides a comprehensive summary of changes, includes a type of change (Bug Fix), explains the problem and context, and covers validation performed.
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.

@JSONbored
JSONbored marked this pull request as ready for review May 26, 2026 02:17
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 26, 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

🤖 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_test.go`:
- Around line 216-219: In the httptest.NewServer(http.HandlerFunc(...)) handler
where you parse body["input"] into inputs and currently call
t.Fatalf("input=%#v", body["input"]) (around the inputs, ok check), replace that
t.Fatalf with t.Errorf to record the failure without aborting the test
goroutine, write an appropriate HTTP error response (e.g., http.Error or setting
status and body), and then return immediately from the handler so the request
completes; this change affects the handler closure that reads body and the
inputs variable check.

In `@internal/entity/models/tokenhub.go`:
- Around line 44-47: Both ChatWithMessages and ChatStreamlyWithSender are
missing validation for an empty modelName; add a guard at the start of
TokenHubModel.ChatWithMessages and TokenHubModel.ChatStreamlyWithSender that
checks modelName is not nil/empty (use strings.TrimSpace(modelName) to catch
whitespace) and return a clear error (e.g., fmt.Errorf("modelName is required"))
if invalid, so bad requests are rejected locally before calling TokenHub.
🪄 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: d312d2fe-849d-4f4e-b5d5-e4d2fb562231

📥 Commits

Reviewing files that changed from the base of the PR and between c3b38d3 and e2637ea.

📒 Files selected for processing (3)
  • internal/entity/models/factory.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenhub_test.go

Comment on lines +216 to +219
inputs, ok := body["input"].([]interface{})
if !ok || len(inputs) != 2 {
t.Fatalf("input=%#v", body["input"])
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n --type=go -C3 'httptest\.NewServer|http\.HandlerFunc|t\.Fatalf\(' internal/entity/models/tokenhub_test.go

Repository: infiniflow/ragflow

Length of output: 5041


Replace t.Fatalf inside the httptest HTTP handler with t.Errorf (+ early return)

internal/entity/models/tokenhub_test.go uses t.Fatalf inside the httptest.NewServer(http.HandlerFunc(...)) closure (around lines 216-219). Change it to t.Errorf and return after writing an error response so the test fails reliably.

💡 Suggested fix
 		inputs, ok := body["input"].([]interface{})
 		if !ok || len(inputs) != 2 {
-			t.Fatalf("input=%#v", body["input"])
+			t.Errorf("input=%#v", body["input"])
+			http.Error(w, "invalid input", http.StatusBadRequest)
+			return
 		}
📝 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
inputs, ok := body["input"].([]interface{})
if !ok || len(inputs) != 2 {
t.Fatalf("input=%#v", body["input"])
}
inputs, ok := body["input"].([]interface{})
if !ok || len(inputs) != 2 {
t.Errorf("input=%#v", body["input"])
http.Error(w, "invalid input", 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/tokenhub_test.go` around lines 216 - 219, In the
httptest.NewServer(http.HandlerFunc(...)) handler where you parse body["input"]
into inputs and currently call t.Fatalf("input=%#v", body["input"]) (around the
inputs, ok check), replace that t.Fatalf with t.Errorf to record the failure
without aborting the test goroutine, write an appropriate HTTP error response
(e.g., http.Error or setting status and body), and then return immediately from
the handler so the request completes; this change affects the handler closure
that reads body and the inputs variable check.

Comment on lines 44 to +47
func (t *TokenHubModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
return nil, fmt.Errorf("api key is required")
}

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

Validate modelName before sending chat requests.

ChatWithMessages and ChatStreamlyWithSender now fail fast for API key/sender, but still allow empty modelName, which pushes avoidable bad requests to TokenHub instead of returning a local validation error.

💡 Suggested fix
 func (t *TokenHubModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) {
+	if strings.TrimSpace(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")
 	}
@@
 func (t *TokenHubModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
+	if strings.TrimSpace(modelName) == "" {
+		return fmt.Errorf("model name is required")
+	}
 	if sender == nil {
 		return fmt.Errorf("sender is required")
 	}

Also applies to: 169-175

🤖 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 44 - 47, Both
ChatWithMessages and ChatStreamlyWithSender are missing validation for an empty
modelName; add a guard at the start of TokenHubModel.ChatWithMessages and
TokenHubModel.ChatStreamlyWithSender that checks modelName is not nil/empty (use
strings.TrimSpace(modelName) to catch whitespace) and return a clear error
(e.g., fmt.Errorf("modelName is required")) if invalid, so bad requests are
rejected locally before calling TokenHub.

@Haruko386 Haruko386 added the ci Continue Integration label May 26, 2026

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

LGTM

@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 (3dbd874) to head (ddc6f80).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15224   +/-   ##
=======================================
  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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants