Repository navigation
Go: implement provider: Jina - #14838
Conversation
📝 WalkthroughWalkthroughThis PR adds Jina model provider support: a JSON config listing Jina endpoints and models, factory dispatch to instantiate ChangesJina Model Provider Integration
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
conf/models/jina.jsoninternal/entity/models/factory.gointernal/entity/models/jina.go
| "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" | ||
| ] | ||
| } | ||
| ] |
There was a problem hiding this comment.
🧩 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:
- 1: https://jina.ai/embeddings/
- 2: https://jina.ai/en-US/reranker/
- 3: https://jina.ai/reranker/
Fix reranker model max_tokens configurations to match Jina API specifications.
The reranker models have incorrect token limits:
jina-reranker-v3: Change 134144 → 131,072jina-reranker-m0: Change 134144 → 10,000jina-reranker-v2-base-multilingual: Change 134144 → 1,024jina-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.
| 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)) |
There was a problem hiding this comment.
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.
| 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.
| 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)) |
There was a problem hiding this comment.
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.
| 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.
| var topN = rerankConfig.TopN | ||
| if rerankConfig.TopN != 0 { | ||
| topN = rerankConfig.TopN | ||
| } |
There was a problem hiding this comment.
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.
| // 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) | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
♻️ Duplicate comments (3)
internal/entity/models/jina.go (2)
135-138:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winRedundant
topNassignment still present.The
if rerankConfig.TopN != 0branch is a no-op since both branches assign the same value. Collapse to a single assignment. Additionally, consider that always emitting"top_n": 0to Jina when unset may cause the API to return zero results — omit the key entirely (e.g., viaomitemptyor a separate request struct) whenTopN == 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
CheckConnectiondoes not validate the API key — it calls an unauthenticated endpoint.
CheckConnectiondelegates toListModels(line 250), which issues aGETrequest to Jina's/modelsendpoint without checking whetherapiConfig.ApiKeyis valid. The endpoint itself is publicly accessible (returns HTTP 200 with or without authentication), soCheckConnectionwill 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 theAuthorizationheader 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 winReranker
max_tokensvalues still inconsistent with Jina API specs.Per Jina documentation, the four reranker models have distinct context-length limits, not the uniform
134144configured here. Suggested corrections:
jina-reranker-v3→131072jina-reranker-m0→10000jina-colbert-v2→8192jina-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
📒 Files selected for processing (3)
conf/models/jina.jsoninternal/entity/models/factory.gointernal/entity/models/jina.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
### 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)
What problem does this PR solve?
This PR completes the Jina provider
The following functionalities are now supported:
Jina:
BalanceVerified examples from the CLI:
Type of change