Skip to content

Go: implement provider: OrcaRouter - #15235

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:main
May 26, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement provider OrcaRouter
The following functionalities are now supported:

Cohere:

  • Chat / Think Chat / Stream Chat / Stream Think Chat
  • Model listing
  • TTS
  • Balance

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 26, 2026
@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: e74a1c40-0492-4275-b323-d130ab360339

📥 Commits

Reviewing files that changed from the base of the PR and between 2d2cc35 and a8ffec1.

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

📝 Walkthrough

Walkthrough

Adds OrcaRouter as a new model provider: configuration, factory registration, and an OrcaRouterModel implementing chat (sync & streaming), TTS, model listing, and several stubbed methods.

Changes

OrcaRouter Model Provider Integration

Layer / File(s) Summary
OrcaRouter configuration
conf/models/orcarouter.json
Configuration defines base API URL, feature-specific URL suffixes for chat/models/tts, and supported models including orcarouter/auto (chat, max_tokens) and openai/tts-1 (tts).
Factory provider registration
internal/entity/models/factory.go
ModelFactory.CreateModelDriver adds a case-insensitive "orcarouter" branch to instantiate OrcaRouterModel with baseURL and urlSuffix.
Driver structure and initialization
internal/entity/models/orcarouter.go
OrcaRouterModel struct with BaseURL, URLSuffix, and configured http.Client; NewOrcaRouterModel, Name, and NewInstance methods.
Chat implementations
internal/entity/models/orcarouter.go
ChatWithMessages validates API key/messages, builds JSON request with optional ChatConfig, posts to chat endpoint, and extracts choices[0].message.content. ChatStreamlyWithSender posts with stream:true, parses SSE data: lines, forwards delta.content to sender, handles [DONE]/finish reasons, and emits final [DONE].
Text-to-speech and model listing
internal/entity/models/orcarouter.go
AudioSpeech validates input, builds TTS JSON with optional TTSConfig params/format, posts and returns raw response bytes. ListModels GETs models endpoint, decodes data entries into model IDs. CheckConnection calls ListModels.
Unsupported method stubs
internal/entity/models/orcarouter.go
Embed, Rerank, Transcribe*, AudioSpeechWithSender, OCRFile, ParseFile, Balance, ListTasks, and ShowTask return "no such method" errors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14832: Extends ModelFactory.CreateModelDriver with a new provider case (baichuan) to instantiate a model driver, following the same integration pattern.

Suggested labels

💞 feature

Poem

🐰 A router hops in, so nimble and bright,
Messages scurry from morning to night,
Streams whisper deltas, chunk by chunk,
Voices bloom—audio pours from the trunk,
Models line up, ready to take flight.

🚥 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 concisely summarizes the main change: implementing a new OrcaRouter provider in Go.
Description check ✅ Passed The description includes the required template sections: problem statement, type of change selection, and provides implementation details with a checklist of supported functionalities.
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 ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 26, 2026
@Haruko386
Haruko386 marked this pull request as draft May 26, 2026 06:16
@Haruko386
Haruko386 marked this pull request as ready for review May 26, 2026 06:16
@dosubot dosubot Bot added the size:L This PR changes 100-499 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: 6

🤖 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/orcarouter.go`:
- Around line 315-318: The AudioSpeech method on OrcaRouterModel dereferences
pointer parameters (modelName and apiConfig.ApiKey) without nil/empty checks
which can cause panics; update AudioSpeech to validate that modelName and
apiConfig are non-nil and that *modelName and apiConfig.ApiKey (and any other
pointer fields used later in the method) are non-empty before use, returning a
descriptive error if invalid. Locate usages inside AudioSpeech (and the adjacent
blocks referenced around the same function) and add the same guard checks where
modelName, apiConfig, or ttsConfig pointer fields are dereferenced so all
nullable inputs are validated consistently.
- Around line 163-166: The ChatStreamlyWithSender function can panic because it
dereferences apiConfig.ApiKey without nil checks; update ChatStreamlyWithSender
to validate that apiConfig is not nil and that apiConfig.ApiKey is not nil/empty
before using *apiConfig.ApiKey (the problematic dereference around lines
223–225), and return a clear error if the API key is missing; ensure any other
uses in this function that access apiConfig or ApiKey follow the same nil/empty
checks.
- Around line 385-389: ListModels currently dereferences *apiConfig.ApiKey (and
accesses apiConfig fields) without nil checks, which can panic when apiConfig or
apiConfig.ApiKey is nil; update ListModels to safely handle nil by first
checking if apiConfig != nil and apiConfig.ApiKey != nil before using
*apiConfig.ApiKey (and similarly guard any other dereferences like
apiConfig.Region), and return a clear error when the API key is missing rather
than allowing a panic; look for references to ListModels, APIConfig, and ApiKey
to apply the guards and the early error return.
- Around line 133-141: The code indexes choices[0] without checking for an empty
slice, which can panic; in the block where you extract choices from result
(variable names choices and firstChoice), first verify len(choices) > 0 and
return an error like "empty choices in response" if it's zero before attempting
choices[0]; then perform the type assertion for firstChoice
(map[string]interface{}) as before. This ensures no out-of-range access when the
provider returns an empty choices array.
- Around line 423-434: The JSON parsing in ListModels uses unchecked type
assertions on result["data"], each model, and modelMap["id"] which can panic;
update the code in the ListModels function to safely validate types and presence
using comma-ok checks (e.g., check result["data"] is []interface{}), iterate
only when that succeeds, check each model is map[string]interface{} before
accessing "id", validate that modelMap["id"] is a string, and return a
descriptive error if any check fails instead of panicking; reference the
variables result, models, modelMap and the place where you currently do
result["data"].([]interface{})/model.(map[string]interface{})/modelMap["id"].(string)
to locate and replace the unsafe assertions.
- Around line 37-39: The NewInstance method currently returns nil; change it to
return a non-nil ModelDriver by creating and returning a new OrcaRouterModel
instance (copying any relevant fields from the receiver o and setting the
provided baseURL map). Make sure to deep-copy or clone the baseURL map (to avoid
shared mutation) and return the pointer cast as ModelDriver so callers receive a
valid, non-nil driver; ensure the returned type satisfies the ModelDriver
interface.
🪄 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: 83a42232-3439-4c38-8a42-6dd62c5889c2

📥 Commits

Reviewing files that changed from the base of the PR and between 036ed5b and 2d2cc35.

📒 Files selected for processing (3)
  • conf/models/orcarouter.json
  • internal/entity/models/factory.go
  • internal/entity/models/orcarouter.go

Comment on lines +37 to +39
func (o *OrcaRouterModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}

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

NewInstance returns nil, which can break caller flow.

Returning nil here can cause downstream nil dereference when a new driver instance is expected.

Proposed fix
 func (o *OrcaRouterModel) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return NewOrcaRouterModel(baseURL, o.URLSuffix)
 }
🤖 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/orcarouter.go` around lines 37 - 39, The NewInstance
method currently returns nil; change it to return a non-nil ModelDriver by
creating and returning a new OrcaRouterModel instance (copying any relevant
fields from the receiver o and setting the provided baseURL map). Make sure to
deep-copy or clone the baseURL map (to avoid shared mutation) and return the
pointer cast as ModelDriver so callers receive a valid, non-nil driver; ensure
the returned type satisfies the ModelDriver interface.

Comment on lines +133 to +141
choices, ok := result["choices"].([]interface{})
if !ok {
return nil, fmt.Errorf("no choices in response")
}

firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("no choices in response")
}

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

Guard empty choices before indexing.

At Line 138, choices[0] can panic when the provider returns an empty choices array.

Proposed fix
-	choices, ok := result["choices"].([]interface{})
-	if !ok {
+	choices, ok := result["choices"].([]interface{})
+	if !ok || len(choices) == 0 {
 		return nil, fmt.Errorf("no choices in response")
 	}
📝 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
choices, ok := result["choices"].([]interface{})
if !ok {
return nil, fmt.Errorf("no choices in response")
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("no choices in response")
}
choices, ok := result["choices"].([]interface{})
if !ok || len(choices) == 0 {
return nil, fmt.Errorf("no choices in response")
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("no choices in response")
}
🤖 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/orcarouter.go` around lines 133 - 141, The code
indexes choices[0] without checking for an empty slice, which can panic; in the
block where you extract choices from result (variable names choices and
firstChoice), first verify len(choices) > 0 and return an error like "empty
choices in response" if it's zero before attempting choices[0]; then perform the
type assertion for firstChoice (map[string]interface{}) as before. This ensures
no out-of-range access when the provider returns an empty choices array.

Comment on lines +163 to +166
func (o *OrcaRouterModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
if len(messages) == 0 {
return fmt.Errorf("messages is empty")
}

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

Streaming chat misses API key validation and can panic.

At Line 224, *apiConfig.ApiKey is dereferenced without checking apiConfig/ApiKey.

Proposed fix
 func (o *OrcaRouterModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return fmt.Errorf("api key is nil or empty")
+	}
 	if len(messages) == 0 {
 		return fmt.Errorf("messages is empty")
 	}

Also applies to: 223-225

🤖 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/orcarouter.go` around lines 163 - 166, The
ChatStreamlyWithSender function can panic because it dereferences
apiConfig.ApiKey without nil checks; update ChatStreamlyWithSender to validate
that apiConfig is not nil and that apiConfig.ApiKey is not nil/empty before
using *apiConfig.ApiKey (the problematic dereference around lines 223–225), and
return a clear error if the API key is missing; ensure any other uses in this
function that access apiConfig or ApiKey follow the same nil/empty checks.

Comment on lines +315 to +318
func (o *OrcaRouterModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("audio content is empty")
}

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

AudioSpeech dereferences nullable inputs without guards.

modelName and apiConfig.ApiKey are used as pointers without validation; this can panic on invalid inputs.

Proposed fix
 func (o *OrcaRouterModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) {
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is nil or empty")
+	}
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
 	if audioContent == nil || *audioContent == "" {
 		return nil, fmt.Errorf("audio content is empty")
 	}

Also applies to: 327-329, 352-353

🤖 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/orcarouter.go` around lines 315 - 318, The AudioSpeech
method on OrcaRouterModel dereferences pointer parameters (modelName and
apiConfig.ApiKey) without nil/empty checks which can cause panics; update
AudioSpeech to validate that modelName and apiConfig are non-nil and that
*modelName and apiConfig.ApiKey (and any other pointer fields used later in the
method) are non-empty before use, returning a descriptive error if invalid.
Locate usages inside AudioSpeech (and the adjacent blocks referenced around the
same function) and add the same guard checks where modelName, apiConfig, or
ttsConfig pointer fields are dereferenced so all nullable inputs are validated
consistently.

Comment on lines +385 to +389
func (o *OrcaRouterModel) ListModels(apiConfig *APIConfig) ([]string, error) {
var region = "default"
if apiConfig != nil && 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

ListModels can panic on nil apiConfig / API key.

Line 406 dereferences *apiConfig.ApiKey without nil checks.

Proposed fix
 func (o *OrcaRouterModel) ListModels(apiConfig *APIConfig) ([]string, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
 	var region = "default"
 	if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}

Also applies to: 405-407

🤖 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/orcarouter.go` around lines 385 - 389, ListModels
currently dereferences *apiConfig.ApiKey (and accesses apiConfig fields) without
nil checks, which can panic when apiConfig or apiConfig.ApiKey is nil; update
ListModels to safely handle nil by first checking if apiConfig != nil and
apiConfig.ApiKey != nil before using *apiConfig.ApiKey (and similarly guard any
other dereferences like apiConfig.Region), and return a clear error when the API
key is missing rather than allowing a panic; look for references to ListModels,
APIConfig, and ApiKey to apply the guards and the early error return.

Comment on lines +423 to +434
// Parse response
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}

// convert result["data"] to []map[string]interface{}
models := make([]string, 0)
for _, model := range result["data"].([]interface{}) {
modelMap := model.(map[string]interface{})
modelName := modelMap["id"].(string)
models = append(models, modelName)

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

Unsafe response assertions in ListModels can panic.

result["data"].([]interface{}), model.(map[string]interface{}), and modelMap["id"].(string) all assume perfect payload shape.

Proposed fix
 	// Parse response
 	var result map[string]interface{}
 	if err = json.Unmarshal(body, &result); err != nil {
 		return nil, fmt.Errorf("failed to parse response: %w", err)
 	}
 
-	// convert result["data"] to []map[string]interface{}
+	data, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("invalid models payload: missing data array")
+	}
+
 	models := make([]string, 0)
-	for _, model := range result["data"].([]interface{}) {
-		modelMap := model.(map[string]interface{})
-		modelName := modelMap["id"].(string)
-		models = append(models, modelName)
+	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)
 	}
📝 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
// Parse response
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
// convert result["data"] to []map[string]interface{}
models := make([]string, 0)
for _, model := range result["data"].([]interface{}) {
modelMap := model.(map[string]interface{})
modelName := modelMap["id"].(string)
models = append(models, modelName)
// Parse response
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
data, ok := result["data"].([]interface{})
if !ok {
return nil, fmt.Errorf("invalid models payload: missing data array")
}
models := make([]string, 0)
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)
}
🤖 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/orcarouter.go` around lines 423 - 434, The JSON
parsing in ListModels uses unchecked type assertions on result["data"], each
model, and modelMap["id"] which can panic; update the code in the ListModels
function to safely validate types and presence using comma-ok checks (e.g.,
check result["data"] is []interface{}), iterate only when that succeeds, check
each model is map[string]interface{} before accessing "id", validate that
modelMap["id"] is a string, and return a descriptive error if any check fails
instead of panicking; reference the variables result, models, modelMap and the
place where you currently do
result["data"].([]interface{})/model.(map[string]interface{})/modelMap["id"].(string)
to locate and replace the unsafe assertions.

@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.16%. Comparing base (036ed5b) to head (a8ffec1).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15235   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  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.

@JinHai-CN
JinHai-CN merged commit 3619cec into infiniflow:main May 26, 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.

2 participants