Skip to content

Go: implement provider: Jina - #14838

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Haruko386:main
May 12, 2026
Merged

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

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

This PR completes the Jina provider

The following functionalities are now supported:

Jina:

  • Chat / Stream Chat (Not available for now: (Jina chat API docs))
  • Embedding
  • Rerank
  • Model listing
  • Provider connection checking
  • Balance

Verified examples from the CLI:

RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'jina-embeddings-v2-base-en@test@jina' dimension 16
+-----------+-------+
| dimension | index |
+-----------+-------+
| 768       | 0     |
| 768       | 1     |
+-----------+-------+

RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'jina-reranker-v2-base-multilingual@test@jina' top 3;
+-------+-----------------+
| index | relevance_score |
+-------+-----------------+
| 0     | 0.74316794      |
| 2     | 0.18713269      |
| 1     | 0.15817434      |
+-------+-----------------+

RAGFlow(user)> list supported models from 'jina' 'test'
+---------------------------------------------+
| model_name                                  |
+---------------------------------------------+
| Jina AI: Jina VLM                           |
| Jina AI: Jina Reranker v3                   |
| Jina AI: Jina Code Embeddings 0.5b          |
| Jina AI: Jina Code Embeddings 1.5b          |
| Jina AI: Jina Embeddings v4                 |
| Jina AI: Jina Reranker M0                   |
| Jina AI: ReaderLM v2                        |
| Jina AI: Jina Clip v2                       |
| Jina AI: Jina Embeddings v3                 |
| Jina AI: Jina Colbert v2                    |
| Jina AI: Reader LM 0.5b                     |
| Jina AI: Reader LM 1.5b                     |
| Jina AI: Jina Reranker v2 Base Multilingual |
| Jina AI: Jina Clip v1                       |
| Jina AI: Jina Reranker v1 Tiny EN           |
| Jina AI: Jina Reranker v1 Turbo EN          |
| Jina AI: Jina Reranker v1 Base EN           |
| Jina AI: Jina Colbert v1 EN                 |
| Jina AI: Jina Embeddings v2 Base ES         |
| Jina AI: Jina Embeddings v2 Base Code       |
| Jina AI: Jina Embeddings v2 Base DE         |
| Jina AI: Jina Embeddings v2 Base ZH         |
| Jina AI: Jina Embeddings v2 Base EN         |
| Jina AI: Jina Embedding B EN v1             |
| Jina AI: Jina Embeddings v5 Text Small      |
| Jina AI: Jina Embeddings v5 Omni Small      |
| Jina AI: Jina Embeddings v5 Omni Nano       |
| Jina AI: Jina Embeddings v5 Text Nano       |
+---------------------------------------------+

RAGFlow(user)> check instance 'test' from 'jina'
SUCCESS

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 12, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 12, 2026
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label May 12, 2026
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds Jina model provider support: a JSON config listing Jina endpoints and models, factory dispatch to instantiate JinaModel, and a JinaModel driver implementing Embed, Rerank, ListModels, CheckConnection, and stubs for chat/balance using HTTP+Bearer auth.

Changes

Jina Model Provider Integration

Layer / File(s) Summary
Jina configuration and factory dispatch
conf/models/jina.json, internal/entity/models/factory.go
Provider config defines base URLs (default, deepsearch), URL suffixes for chat/models/embedding/rerank, and a models array with model entries; factory adds a "jina" case to return NewJinaModel.
JinaModel struct and constructors
internal/entity/models/jina.go
Adds JinaModel type, NewJinaModel and NewInstance, and a shared http.Client with 90s timeout.
JinaModel API implementations and stubs
internal/entity/models/jina.go
Implements Embed and Rerank (region-aware POSTs, bearer auth, JSON parsing, HTTP 200 checks), ListModels (GET + parse), CheckConnection (delegates to ListModels), Balance (not supported error), and chat methods as "not implemented" stubs.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant JinaModel
  participant JinaAPI
  Client->>JinaModel: Embed(modelName, texts, apiConfig)
  JinaModel->>JinaAPI: POST /embeddings (bearer token, JSON)
  JinaAPI-->>JinaModel: 200 OK + JSON {data: [...]}
  JinaModel-->>Client: []EmbeddingData

  Client->>JinaModel: Rerank(modelName, query, documents, apiConfig)
  JinaModel->>JinaAPI: POST /rerank (bearer token, JSON with top_n)
  JinaAPI-->>JinaModel: 200 OK + JSON {results: [...]}
  JinaModel-->>Client: RerankResponse

  Client->>JinaModel: ListModels(apiConfig)
  JinaModel->>JinaAPI: GET /models (region)
  JinaAPI-->>JinaModel: 200 OK + JSON {data: [...]}
  JinaModel-->>Client: []string

  Client->>JinaModel: CheckConnection(apiConfig)
  JinaModel->>JinaModel: calls ListModels
  JinaModel-->>Client: error or nil
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A tiny rabbit hops to say hello,
Jina models join the data flow,
With POSTs and tokens, JSON in stride,
Embeddings, reranks now abide,
New provider seeds the RAGgarden's glow.

🚥 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 'Go: implement provider: Jina' clearly and concisely describes the main change—adding Jina provider implementation.
Description check ✅ Passed The description follows the template with a problem statement, comprehensive implementation details, verified examples, and a checked type-of-change checkbox.
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.

@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 `@conf/models/jina.json`:
- Around line 14-99: Update the reranker model max_tokens to match Jina API: set
"jina-reranker-v3" max_tokens to 131072, "jina-reranker-m0" max_tokens to 10000,
"jina-reranker-v2-base-multilingual" max_tokens to 1024, and "jina-colbert-v2"
max_tokens to 8192 in the conf/models/jina.json models array (look for the
entries by name). Also verify whether the "jina-embeddings-v5-*" entries
("jina-embeddings-v5-text-small", "jina-embeddings-v5-text-nano",
"jina-embeddings-v5-omni-small", "jina-embeddings-v5-omni-nano") are valid per
current Jina docs and adjust or remove them if they are not official.

In `@internal/entity/models/jina.go`:
- Around line 135-138: The current code redundantly assigns topN from
rerankConfig.TopN twice; remove the if block and replace with a single direct
assignment (e.g., set topN = rerankConfig.TopN or declare topN :=
rerankConfig.TopN) so only one assignment exists; ensure any intended default
behavior for zero is handled explicitly elsewhere if needed.
- Around line 123-158: The Rerank method on JinaModel dereferences pointers
without validation (modelName and apiConfig.ApiKey) which can panic; add nil
checks at the start of Jerank (Rerank) to validate that modelName != nil and
*modelName != "" and that apiConfig != nil and apiConfig.ApiKey != nil (and
optionally non-empty), returning a descriptive error if any are invalid, then
proceed to use *modelName and *apiConfig.ApiKey; keep existing behavior for
region and topN intact.
- Around line 234-240: The loop over result["data"] uses unsafe type assertions
that may panic; change it to use comma-ok checks: first assert result["data"] is
a []interface{} using v,ok := result["data"].([]interface{}), handle the false
case (return error or empty slice), then inside the loop assert each item to
map[string]interface{} with mm,ok := model.(map[string]interface{}) and check
for the "name" key using nameVal,ok := mm["name"], then assert nameStr,ok :=
nameVal.(string) before appending to models; update the code around the models,
modelMap and modelName variables to follow this safe pattern and handle failures
gracefully.
- Around line 52-80: In Embed (receiver JinaModel) add explicit nil/empty
validation for modelName and apiConfig.ApiKey before dereferencing: ensure
modelName != nil and *modelName != "" and return a descriptive error if invalid;
ensure apiConfig != nil and apiConfig.ApiKey != nil and *apiConfig.ApiKey != ""
before using it and return an error if invalid; keep existing region handling
but move the modelName nil-check to occur before constructing reqBody and the
apiConfig.ApiKey check before setting the Authorization header to avoid panics.
🪄 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: fd819326-fdcf-4472-b982-a35b35f3a829

📥 Commits

Reviewing files that changed from the base of the PR and between eaa2e46 and dc81173.

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

Comment thread conf/models/jina.json
Comment on lines +14 to +99
"models": [
{
"name": "jina-reranker-v3",
"max_tokens": 134144,
"model_types": [
"rerank"
]
},
{
"name": "jina-reranker-m0",
"max_tokens": 134144,
"model_types": [
"rerank"
]
},
{
"name": "jina-colbert-v2",
"max_tokens": 134144,
"model_types": [
"rerank"
]
},
{
"name": "jina-reranker-v2-base-multilingual",
"max_tokens": 134144,
"model_types": [
"rerank"
]
},
{
"name": "jina-embeddings-v3",
"max_tokens": 8192,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v4",
"max_tokens": 32768,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v5-text-small",
"max_tokens": 32768,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v5-text-nano",
"max_tokens": 8192,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v5-omni-small",
"max_tokens": 32768,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v5-omni-nano",
"max_tokens": 8192,
"model_types": [
"embedding"
]
},
{
"name": "jina-clip-v2",
"max_tokens": 8192,
"model_types": [
"embedding"
]
},
{
"name": "jina-embeddings-v2-base-en",
"max_tokens": 8192,
"model_types": [
"embedding"
]
}
]

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

🧩 Analysis chain

🌐 Web query:

What are the current Jina AI models and their maximum token limits for embeddings and reranking?

💡 Result:

Current Jina AI embedding and reranking models (via Jina’s API) and their maximum token limits: Embeddings (maximum context length per input) - jina-embeddings-v4: 32,768 tokens [1] - jina-embeddings-v3: 8,192 tokens [1] - jina-embeddings-v2-: 8,192 tokens (includes v2 base variants like base-en/base-de/base-zh, etc.) [1] - jina-clip-v1/v2: 8,192 tokens [1] - jina-colbert-v1/v2: 8,192 tokens [1] - jina-code-embeddings-: 32,768 tokens [1] Rerankers (maximum context length; query + documents combined, unless otherwise noted) - jina-reranker-v3: 131,072 tokens (query + all documents combined) [2][3] - jina-reranker-m0: 10,000 tokens [2][3] - jina-reranker-v2-base-multilingual: 1,024 tokens (auto chunking for longer documents) [2][3] - jina-reranker-v1-*: 1,024 tokens (queries auto-truncated and long documents auto chunked) [2][3] - jina-colbert-v2: 8,192 tokens [2][3] Notes - Jina’s reranker endpoint truncates or chunks inputs that exceed each model’s maximum token limit (behavior varies by reranker family/model). [2][3]

Citations:


Fix reranker model max_tokens configurations to match Jina API specifications.

The reranker models have incorrect token limits:

  • jina-reranker-v3: Change 134144 → 131,072
  • jina-reranker-m0: Change 134144 → 10,000
  • jina-reranker-v2-base-multilingual: Change 134144 → 1,024
  • jina-colbert-v2: Change 134144 → 8,192

Verify the v5 embedding models (v5-text-small, v5-text-nano, v5-omni-small, v5-omni-nano) against current Jina documentation as they are not found in official API references.

🤖 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 `@conf/models/jina.json` around lines 14 - 99, Update the reranker model
max_tokens to match Jina API: set "jina-reranker-v3" max_tokens to 131072,
"jina-reranker-m0" max_tokens to 10000, "jina-reranker-v2-base-multilingual"
max_tokens to 1024, and "jina-colbert-v2" max_tokens to 8192 in the
conf/models/jina.json models array (look for the entries by name). Also verify
whether the "jina-embeddings-v5-*" entries ("jina-embeddings-v5-text-small",
"jina-embeddings-v5-text-nano", "jina-embeddings-v5-omni-small",
"jina-embeddings-v5-omni-nano") are valid per current Jina docs and adjust or
remove them if they are not official.

Comment on lines +52 to +80
func (j *JinaModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
if len(texts) == 0 {
return []EmbeddingData{}, nil
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

reqBody := map[string]interface{}{
"model": *modelName,
"input": texts,
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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

Add nil checks to prevent panic.

The function dereferences *modelName (line 65) and *apiConfig.ApiKey (line 80) without nil checks. If modelName is nil or if apiConfig is nil, the function will panic.

🛡️ Proposed fix to add nil validation
 func (j *JinaModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
+	if modelName == nil {
+		return nil, fmt.Errorf("modelName cannot be nil")
+	}
+	if apiConfig == nil || apiConfig.ApiKey == nil {
+		return nil, fmt.Errorf("apiConfig and ApiKey cannot be nil")
+	}
+
 	if len(texts) == 0 {
 		return []EmbeddingData{}, nil
 	}
📝 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
func (j *JinaModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
if len(texts) == 0 {
return []EmbeddingData{}, nil
}
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", j.BaseURL[region], j.URLSuffix.Embedding)
reqBody := map[string]interface{}{
"model": *modelName,
"input": texts,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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))
func (j *JinaModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
if modelName == nil {
return nil, fmt.Errorf("modelName cannot be nil")
}
if apiConfig == nil || apiConfig.ApiKey == nil {
return nil, fmt.Errorf("apiConfig and ApiKey cannot be nil")
}
if len(texts) == 0 {
return []EmbeddingData{}, nil
}
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", j.BaseURL[region], j.URLSuffix.Embedding)
reqBody := map[string]interface{}{
"model": *modelName,
"input": texts,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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))
🤖 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/jina.go` around lines 52 - 80, In Embed (receiver
JinaModel) add explicit nil/empty validation for modelName and apiConfig.ApiKey
before dereferencing: ensure modelName != nil and *modelName != "" and return a
descriptive error if invalid; ensure apiConfig != nil and apiConfig.ApiKey !=
nil and *apiConfig.ApiKey != "" before using it and return an error if invalid;
keep existing region handling but move the modelName nil-check to occur before
constructing reqBody and the apiConfig.ApiKey check before setting the
Authorization header to avoid panics.

Comment on lines +123 to +158
func (j *JinaModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
if len(documents) == 0 {
return &RerankResponse{}, nil
}

var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}

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

var topN = rerankConfig.TopN
if rerankConfig.TopN != 0 {
topN = rerankConfig.TopN
}

reqBody := map[string]interface{}{
"model": *modelName,
"query": query,
"documents": documents,
"top_n": topN,
}

jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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

Add nil checks to prevent panic.

Similar to Embed, this function dereferences *modelName (line 141) and *apiConfig.ApiKey (line 158) without nil checks, which will panic if either is nil.

🛡️ Proposed fix to add nil validation
 func (j *JinaModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
+	if modelName == nil {
+		return nil, fmt.Errorf("modelName cannot be nil")
+	}
+	if apiConfig == nil || apiConfig.ApiKey == nil {
+		return nil, fmt.Errorf("apiConfig and ApiKey cannot be nil")
+	}
+
 	if len(documents) == 0 {
 		return &RerankResponse{}, nil
 	}
📝 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
func (j *JinaModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
if len(documents) == 0 {
return &RerankResponse{}, nil
}
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", j.BaseURL[region], j.URLSuffix.Rerank)
var topN = rerankConfig.TopN
if rerankConfig.TopN != 0 {
topN = rerankConfig.TopN
}
reqBody := map[string]interface{}{
"model": *modelName,
"query": query,
"documents": documents,
"top_n": topN,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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))
func (j *JinaModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
if modelName == nil {
return nil, fmt.Errorf("modelName cannot be nil")
}
if apiConfig == nil || apiConfig.ApiKey == nil {
return nil, fmt.Errorf("apiConfig and ApiKey cannot be nil")
}
if len(documents) == 0 {
return &RerankResponse{}, nil
}
var region = "default"
if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
url := fmt.Sprintf("%s/%s", j.BaseURL[region], j.URLSuffix.Rerank)
var topN = rerankConfig.TopN
if rerankConfig.TopN != 0 {
topN = rerankConfig.TopN
}
reqBody := map[string]interface{}{
"model": *modelName,
"query": query,
"documents": documents,
"top_n": topN,
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
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))
🤖 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/jina.go` around lines 123 - 158, The Rerank method on
JinaModel dereferences pointers without validation (modelName and
apiConfig.ApiKey) which can panic; add nil checks at the start of Jerank
(Rerank) to validate that modelName != nil and *modelName != "" and that
apiConfig != nil and apiConfig.ApiKey != nil (and optionally non-empty),
returning a descriptive error if any are invalid, then proceed to use *modelName
and *apiConfig.ApiKey; keep existing behavior for region and topN intact.

Comment on lines +135 to +138
var topN = rerankConfig.TopN
if rerankConfig.TopN != 0 {
topN = rerankConfig.TopN
}

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

Remove redundant topN assignment logic.

The condition always assigns topN = rerankConfig.TopN regardless of the if-check. The logic appears incomplete or unnecessary.

♻️ Proposed fix
-	var topN = rerankConfig.TopN
-	if rerankConfig.TopN != 0 {
-		topN = rerankConfig.TopN
-	}
+	topN := rerankConfig.TopN
🤖 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/jina.go` around lines 135 - 138, The current code
redundantly assigns topN from rerankConfig.TopN twice; remove the if block and
replace with a single direct assignment (e.g., set topN = rerankConfig.TopN or
declare topN := rerankConfig.TopN) so only one assignment exists; ensure any
intended default behavior for zero is handled explicitly elsewhere if needed.

Comment on lines +234 to +240
// convert result["data"] to []map[string]interface{}
models := make([]string, 0)
for _, model := range result["data"].([]interface{}) {
modelMap := model.(map[string]interface{})
modelName := modelMap["name"].(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 | 🔴 Critical | ⚡ Quick win

Replace unsafe type assertions with safe checks.

The type assertions at lines 236-239 will panic if the API response structure doesn't match expectations. Use the comma-ok idiom for safe type assertions.

🛡️ Proposed fix with safe type assertions
-	// convert result["data"] to []map[string]interface{}
 	models := make([]string, 0)
-	for _, model := range result["data"].([]interface{}) {
-		modelMap := model.(map[string]interface{})
-		modelName := modelMap["name"].(string)
+	data, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("unexpected response format: 'data' field is not an array")
+	}
+	for _, model := range data {
+		modelMap, ok := model.(map[string]interface{})
+		if !ok {
+			continue
+		}
+		modelName, ok := modelMap["name"].(string)
+		if !ok {
+			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/jina.go` around lines 234 - 240, The loop over
result["data"] uses unsafe type assertions that may panic; change it to use
comma-ok checks: first assert result["data"] is a []interface{} using v,ok :=
result["data"].([]interface{}), handle the false case (return error or empty
slice), then inside the loop assert each item to map[string]interface{} with
mm,ok := model.(map[string]interface{}) and check for the "name" key using
nameVal,ok := mm["name"], then assert nameStr,ok := nameVal.(string) before
appending to models; update the code around the models, modelMap and modelName
variables to follow this safe pattern and handle failures gracefully.

@JinHai-CN
JinHai-CN marked this pull request as draft May 12, 2026 09:20
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 12, 2026 09:20
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 12, 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.

♻️ Duplicate comments (3)
internal/entity/models/jina.go (2)

135-138: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Redundant topN assignment still present.

The if rerankConfig.TopN != 0 branch is a no-op since both branches assign the same value. Collapse to a single assignment. Additionally, consider that always emitting "top_n": 0 to Jina when unset may cause the API to return zero results — omit the key entirely (e.g., via omitempty or a separate request struct) when TopN == 0.

♻️ Proposed fix
-	var topN = rerankConfig.TopN
-	if rerankConfig.TopN != 0 {
-		topN = rerankConfig.TopN
-	}
-
 	reqBody := map[string]interface{}{
 		"model":     *modelName,
 		"query":     query,
 		"documents": documents,
-		"top_n":     topN,
+	}
+	if rerankConfig != nil && rerankConfig.TopN != 0 {
+		reqBody["top_n"] = rerankConfig.TopN
 	}
🤖 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/jina.go` around lines 135 - 138, Collapse the
redundant topN assignment by removing the unnecessary if-branch and assign topN
directly from rerankConfig.TopN (remove the duplicate conditional around the
variable in the code that references rerankConfig.TopN). Then ensure the Jina
request omits the "top_n" field when TopN == 0 instead of sending 0 — either add
`omitempty` to the request struct field or build a separate request payload that
only sets TopN when rerankConfig.TopN > 0; update the code that marshals/sends
the request (the place constructing the Jina request body) so it conditionally
includes top_n based on rerankConfig.TopN.

198-243: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

CheckConnection does not validate the API key — it calls an unauthenticated endpoint.

CheckConnection delegates to ListModels (line 250), which issues a GET request to Jina's /models endpoint without checking whether apiConfig.ApiKey is valid. The endpoint itself is publicly accessible (returns HTTP 200 with or without authentication), so CheckConnection will always succeed regardless of whether the supplied API key is empty, invalid, or correct. This produces false positives in connection-validation UX: the check appears to pass even when credentials are wrong.

To fix this, call an authenticated endpoint (embedding or rerank) that actually validates the API key, rather than a public endpoint. Note that other methods in this model (Embed, Rerank) already set the Authorization header correctly, so the pattern exists.

Additionally, the unchecked type assertions at lines 236–239 will panic if the response shape differs from expectations (e.g., malformed error responses). These should be replaced with safe assertions that handle unexpected response formats gracefully.

Type assertion safety fix
-	// convert result["data"] to []map[string]interface{}
 	models := make([]string, 0)
-	for _, model := range result["data"].([]interface{}) {
-		modelMap := model.(map[string]interface{})
-		modelName := modelMap["name"].(string)
+	data, ok := result["data"].([]interface{})
+	if !ok {
+		return nil, fmt.Errorf("unexpected response format: 'data' field is not an array")
+	}
+	for _, model := range data {
+		modelMap, ok := model.(map[string]interface{})
+		if !ok {
+			continue
+		}
+		modelName, ok := modelMap["name"].(string)
+		if !ok {
+			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/jina.go` around lines 198 - 243, CheckConnection
wrongly uses the public ListModels endpoint so it never validates
apiConfig.ApiKey; change CheckConnection to call an authenticated endpoint
(reuse the pattern in JinaModel.Embed or JinaModel.Rerank) and ensure the
request sets the Authorization header with apiConfig.ApiKey so the API key is
actually validated. In JinaModel.ListModels also replace all unchecked type
assertions (result["data"].([]interface{}), model.(map[string]interface{}),
modelMap["name"].(string)) with safe checks (ok-style type assertions), return a
clear error if the shape is unexpected, and handle non-array or missing data
without panicking. Ensure any new authenticated request honors the same
BaseURL/URLSuffix logic and uses j.httpClient like existing methods.
conf/models/jina.json (1)

16-42: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reranker max_tokens values still inconsistent with Jina API specs.

Per Jina documentation, the four reranker models have distinct context-length limits, not the uniform 134144 configured here. Suggested corrections:

  • jina-reranker-v3 → 131072
  • jina-reranker-m0 → 10000
  • jina-colbert-v2 → 8192
  • jina-reranker-v2-base-multilingual → 1024
♻️ Proposed fix
     {
       "name": "jina-reranker-v3",
-      "max_tokens": 134144,
+      "max_tokens": 131072,
       "model_types": [
         "rerank"
       ]
     },
     {
       "name": "jina-reranker-m0",
-      "max_tokens": 134144,
+      "max_tokens": 10000,
       "model_types": [
         "rerank"
       ]
     },
     {
       "name": "jina-colbert-v2",
-      "max_tokens": 134144,
+      "max_tokens": 8192,
       "model_types": [
         "rerank"
       ]
     },
     {
       "name": "jina-reranker-v2-base-multilingual",
-      "max_tokens": 134144,
+      "max_tokens": 1024,
       "model_types": [
         "rerank"
       ]
     },
🤖 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 `@conf/models/jina.json` around lines 16 - 42, The JSON entries for the rerank
models have incorrect uniform max_tokens; update the max_tokens values for the
specific model objects "jina-reranker-v3", "jina-reranker-m0",
"jina-colbert-v2", and "jina-reranker-v2-base-multilingual" to match Jina specs
by setting "jina-reranker-v3" -> 131072, "jina-reranker-m0" -> 10000,
"jina-colbert-v2" -> 8192, and "jina-reranker-v2-base-multilingual" -> 1024 so
each model object uses its correct context-length limit.
🤖 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.

Duplicate comments:
In `@conf/models/jina.json`:
- Around line 16-42: The JSON entries for the rerank models have incorrect
uniform max_tokens; update the max_tokens values for the specific model objects
"jina-reranker-v3", "jina-reranker-m0", "jina-colbert-v2", and
"jina-reranker-v2-base-multilingual" to match Jina specs by setting
"jina-reranker-v3" -> 131072, "jina-reranker-m0" -> 10000, "jina-colbert-v2" ->
8192, and "jina-reranker-v2-base-multilingual" -> 1024 so each model object uses
its correct context-length limit.

In `@internal/entity/models/jina.go`:
- Around line 135-138: Collapse the redundant topN assignment by removing the
unnecessary if-branch and assign topN directly from rerankConfig.TopN (remove
the duplicate conditional around the variable in the code that references
rerankConfig.TopN). Then ensure the Jina request omits the "top_n" field when
TopN == 0 instead of sending 0 — either add `omitempty` to the request struct
field or build a separate request payload that only sets TopN when
rerankConfig.TopN > 0; update the code that marshals/sends the request (the
place constructing the Jina request body) so it conditionally includes top_n
based on rerankConfig.TopN.
- Around line 198-243: CheckConnection wrongly uses the public ListModels
endpoint so it never validates apiConfig.ApiKey; change CheckConnection to call
an authenticated endpoint (reuse the pattern in JinaModel.Embed or
JinaModel.Rerank) and ensure the request sets the Authorization header with
apiConfig.ApiKey so the API key is actually validated. In JinaModel.ListModels
also replace all unchecked type assertions (result["data"].([]interface{}),
model.(map[string]interface{}), modelMap["name"].(string)) with safe checks
(ok-style type assertions), return a clear error if the shape is unexpected, and
handle non-array or missing data without panicking. Ensure any new authenticated
request honors the same BaseURL/URLSuffix logic and uses j.httpClient like
existing methods.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 60c8fb57-4b32-4fdd-a640-3ea979a2c3b3

📥 Commits

Reviewing files that changed from the base of the PR and between eaa2e46 and dc81173.

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

@codecov

codecov Bot commented May 12, 2026

Copy link
Copy Markdown

Codecov Report

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

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

@JinHai-CN
JinHai-CN merged commit 45ee5ca into infiniflow:main May 12, 2026
1 check passed
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?

This PR completes the Jina provider

**The following functionalities are now supported:**

**Jina:**
- [ ] Chat / Stream Chat (Not available for now: [(Jina chat API
docs)](https://api.jina.ai/docs#/Search%20Foundation%20Models/chat_completions_v1_chat_completions_post))
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] ~~Balance~~

**Verified examples from the CLI:**

```plaintext
RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'jina-embeddings-v2-base-en@test@jina' dimension 16
+-----------+-------+
| dimension | index |
+-----------+-------+
| 768       | 0     |
| 768       | 1     |
+-----------+-------+

RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'jina-reranker-v2-base-multilingual@test@jina' top 3;
+-------+-----------------+
| index | relevance_score |
+-------+-----------------+
| 0     | 0.74316794      |
| 2     | 0.18713269      |
| 1     | 0.15817434      |
+-------+-----------------+

RAGFlow(user)> list supported models from 'jina' 'test'
+---------------------------------------------+
| model_name                                  |
+---------------------------------------------+
| Jina AI: Jina VLM                           |
| Jina AI: Jina Reranker v3                   |
| Jina AI: Jina Code Embeddings 0.5b          |
| Jina AI: Jina Code Embeddings 1.5b          |
| Jina AI: Jina Embeddings v4                 |
| Jina AI: Jina Reranker M0                   |
| Jina AI: ReaderLM v2                        |
| Jina AI: Jina Clip v2                       |
| Jina AI: Jina Embeddings v3                 |
| Jina AI: Jina Colbert v2                    |
| Jina AI: Reader LM 0.5b                     |
| Jina AI: Reader LM 1.5b                     |
| Jina AI: Jina Reranker v2 Base Multilingual |
| Jina AI: Jina Clip v1                       |
| Jina AI: Jina Reranker v1 Tiny EN           |
| Jina AI: Jina Reranker v1 Turbo EN          |
| Jina AI: Jina Reranker v1 Base EN           |
| Jina AI: Jina Colbert v1 EN                 |
| Jina AI: Jina Embeddings v2 Base ES         |
| Jina AI: Jina Embeddings v2 Base Code       |
| Jina AI: Jina Embeddings v2 Base DE         |
| Jina AI: Jina Embeddings v2 Base ZH         |
| Jina AI: Jina Embeddings v2 Base EN         |
| Jina AI: Jina Embedding B EN v1             |
| Jina AI: Jina Embeddings v5 Text Small      |
| Jina AI: Jina Embeddings v5 Omni Small      |
| Jina AI: Jina Embeddings v5 Omni Nano       |
| Jina AI: Jina Embeddings v5 Text Nano       |
+---------------------------------------------+

RAGFlow(user)> check instance 'test' from 'jina'
SUCCESS
```

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
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. 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