Skip to content

Go: implement remaining interface for OpenRouter - #14657

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 8, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. implement rerank, embedding, balance, checkConnet method for OpenRouter
  2. delete chat method in internal/entity/models/volcengine.go

Type of change

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

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 8, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 8, 2026
@dosubot dosubot Bot added ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels May 8, 2026
@Haruko386
Haruko386 marked this pull request as draft May 8, 2026 05:06
@Haruko386
Haruko386 marked this pull request as ready for review May 8, 2026 05:06
@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds OpenRouter URL routes and implements embedding (Encode), rerank, balance, and CheckConnection; removes VolcEngine single-message Chat and consolidates chat into ChatWithMessages and streaming ChatStreamlyWithSender.

Changes

OpenRouter Feature Expansion

Layer / File(s) Summary
Configuration Endpoints
conf/models/openrouter.json
URL suffix mappings added for models, embedding, rerank, and balance.
Rerank Types
internal/entity/models/openrouter.go
OpenRouterRerankRequest / OpenRouterRerankResponse structs added for rerank schema.
API Method Implementations
internal/entity/models/openrouter.go
Encode implemented for embeddings (region URL, POST, assemble [][]float64); Rerank implemented using new types; Balance implemented (credits/usage→balance); CheckConnection delegates to Balance.

VolcEngine Chat Consolidation

Layer / File(s) Summary
Chat API Surface
internal/entity/models/volcengine.go
Single-message Chat removed; ChatWithMessages added requiring non-empty messages, region selection, and mapping of thinking/effort to reasoning fields.
Streaming Handler
internal/entity/models/volcengine.go
ChatStreamlyWithSender parses SSE data: lines, extracts delta.content and delta.reasoning_content, forwards chunks via sender, and emits final "[DONE]".
Utilities / Non-chat methods
internal/entity/models/volcengine.go
Other non-chat methods remain unimplemented; CheckConnection performs a region-scoped GET expecting HTTP 200.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through routes and opened doors,
Embeddings nested, reranks on the floor.
VolcEngine now speaks in fuller streams,
Messages gather, reasoning redeems.
Endpoints hum as regions align, hooray for the new chore!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title directly describes the main change: implementing remaining interface methods for OpenRouter, which matches the primary content of the changeset.
Description check ✅ Passed The PR description follows the template structure with both required sections: 'What problem does this PR solve' (listing the specific methods implemented and removed) and 'Type of change' (marked as New Feature and Refactoring).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@codecov

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (f063e03) to head (2a010d8).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14657   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/openrouter.go (1)

483-504: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Rerank needs nil/empty validation for inputs before pointer dereference.

At Line 484 and Line 503, modelName and apiConfig.ApiKey are dereferenced with no guards. This can panic instead of returning a typed error.

Suggested fix
 func (o *OpenRouterModel) Rerank(modelName *string, query string, texts []string, apiConfig *APIConfig) ([]float64, error) {
 	if len(texts) == 0 {
 		return []float64{}, nil
 	}
+	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")
+	}
 
 	var region = "default"
🤖 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/openrouter.go` around lines 483 - 504, The Rerank
implementation dereferences modelName and apiConfig.ApiKey without checks, which
can panic; in the Rerank function add explicit guards that validate modelName is
non-nil and non-empty and that apiConfig and apiConfig.ApiKey are
non-nil/non-empty before using them, returning a clear typed error (e.g.,
fmt.Errorf) instead of proceeding; update the code paths that build
OpenRouterRerankRequest (referencing modelName) and the request header
Authorization (referencing apiConfig.ApiKey) to rely on these validations.
🤖 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/openrouter.go`:
- Around line 366-368: The Encode function currently dereferences modelName
(used when building reqBody) without checking for nil/empty, which can panic;
update Encode to validate modelName before dereferencing: check that the pointer
modelName is non-nil and that *modelName is not an empty string, return a clear
error if invalid, and only then use *modelName when constructing reqBody (or use
a safe local variable). Ensure references to modelName, Encode, and reqBody are
updated accordingly.
- Around line 595-608: The Balance function currently dereferences apiConfig and
apiConfig.ApiKey (and uses apiConfig.Region) without nil/empty checks which can
panic; update Balance (and by extension CheckConnection which calls it) to first
validate apiConfig != nil and apiConfig.ApiKey != nil and non-empty before using
*apiConfig.ApiKey, and handle missing apiConfig/ApiKey by returning a clear
error instead of panicking; also guard Region access by checking
apiConfig.Region != nil/empty before reading and keep using o.BaseURL and
o.URLSuffix.Balance as before.

---

Outside diff comments:
In `@internal/entity/models/openrouter.go`:
- Around line 483-504: The Rerank implementation dereferences modelName and
apiConfig.ApiKey without checks, which can panic; in the Rerank function add
explicit guards that validate modelName is non-nil and non-empty and that
apiConfig and apiConfig.ApiKey are non-nil/non-empty before using them,
returning a clear typed error (e.g., fmt.Errorf) instead of proceeding; update
the code paths that build OpenRouterRerankRequest (referencing modelName) and
the request header Authorization (referencing apiConfig.ApiKey) to rely on these
validations.
🪄 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: 23bf7cdf-ea2e-4e8f-8551-8537ee7ea6ff

📥 Commits

Reviewing files that changed from the base of the PR and between f063e03 and 2a010d8.

📒 Files selected for processing (3)
  • conf/models/openrouter.json
  • internal/entity/models/openrouter.go
  • internal/entity/models/volcengine.go
💤 Files with no reviewable changes (1)
  • internal/entity/models/volcengine.go

Comment on lines +366 to +368
reqBody := map[string]interface{}{
"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

Guard modelName before dereference in Encode (panic risk).

At Line 367, *modelName is used without validating modelName != nil (and non-empty), which can panic on invalid caller input.

Suggested fix
 func (o *OpenRouterModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
 	if len(texts) == 0 {
 		return [][]float64{}, nil
 	}
+	if modelName == nil || *modelName == "" {
+		return nil, fmt.Errorf("model name is nil or empty")
+	}
 
 	var region = "default"
📝 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
reqBody := map[string]interface{}{
"model": *modelName,
"input": texts,
func (o *OpenRouterModel) Encode(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([][]float64, error) {
if len(texts) == 0 {
return [][]float64{}, nil
}
if modelName == nil || *modelName == "" {
return nil, fmt.Errorf("model name is nil or empty")
}
var region = "default"
reqBody := map[string]interface{}{
"model": *modelName,
"input": texts,
🤖 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/openrouter.go` around lines 366 - 368, The Encode
function currently dereferences modelName (used when building reqBody) without
checking for nil/empty, which can panic; update Encode to validate modelName
before dereferencing: check that the pointer modelName is non-nil and that
*modelName is not an empty string, return a clear error if invalid, and only
then use *modelName when constructing reqBody (or use a safe local variable).
Ensure references to modelName, Encode, and reqBody are updated accordingly.

Comment on lines +595 to +608
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

url := fmt.Sprintf("%s/%s", o.BaseURL[region], o.URLSuffix.Balance)

req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

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

Balance can panic on missing apiConfig / API key.

At Line 607, *apiConfig.ApiKey is dereferenced without validation. This is a crash path and also impacts CheckConnection (Line 646) since it delegates to Balance.

Suggested fix
 func (o *OpenRouterModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
 	region := "default"
 	if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
 		region = *apiConfig.Region
 	}
🤖 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/openrouter.go` around lines 595 - 608, The Balance
function currently dereferences apiConfig and apiConfig.ApiKey (and uses
apiConfig.Region) without nil/empty checks which can panic; update Balance (and
by extension CheckConnection which calls it) to first validate apiConfig != nil
and apiConfig.ApiKey != nil and non-empty before using *apiConfig.ApiKey, and
handle missing apiConfig/ApiKey by returning a clear error instead of panicking;
also guard Region access by checking apiConfig.Region != nil/empty before
reading and keep using o.BaseURL and o.URLSuffix.Balance as before.

@JinHai-CN
JinHai-CN merged commit d13a240 into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
### What problem does this PR solve?

1. implement `rerank`, `embedding`, `balance`, `checkConnet` method for
`OpenRouter`
2. delete `chat` method in `internal/entity/models/volcengine.go`

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

1. implement `rerank`, `embedding`, `balance`, `checkConnet` method for
`OpenRouter`
2. delete `chat` method in `internal/entity/models/volcengine.go`

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code 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