2026-06-03 16:33:58 +08:00
|
|
|
//
|
|
|
|
|
// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
|
//
|
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
//
|
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
|
// limitations under the License.
|
|
|
|
|
//
|
|
|
|
|
|
2026-05-12 18:03:05 +08:00
|
|
|
package models
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
"context"
|
2026-05-12 18:03:05 +08:00
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
2026-07-18 21:02:07 +08:00
|
|
|
"ragflow/internal/common"
|
2026-06-04 17:50:22 +08:00
|
|
|
"strings"
|
2026-05-12 18:03:05 +08:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type JinaModel struct {
|
2026-06-04 17:50:22 +08:00
|
|
|
baseModel BaseModel
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewJinaModel(baseURL map[string]string, urlSuffix URLSuffix) *JinaModel {
|
2026-06-11 05:20:12 -06:00
|
|
|
// Embed/Rerank/ListModels issue requests without a per-call context
|
|
|
|
|
// deadline, so keep an explicit 90s client-level timeout to bound them.
|
|
|
|
|
// Built on the shared transport via NewDriverHTTPClient.
|
2026-07-31 19:15:38 +08:00
|
|
|
client := NewDriverHTTPClient(false)
|
2026-06-11 05:20:12 -06:00
|
|
|
client.Timeout = 90 * time.Second
|
2026-05-12 18:03:05 +08:00
|
|
|
return &JinaModel{
|
2026-06-04 17:50:22 +08:00
|
|
|
baseModel: BaseModel{
|
2026-06-11 05:20:12 -06:00
|
|
|
BaseURL: baseURL,
|
|
|
|
|
URLSuffix: urlSuffix,
|
|
|
|
|
httpClient: client,
|
2026-05-12 18:03:05 +08:00
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (j *JinaModel) NewInstance(baseURL map[string]string) ModelDriver {
|
2026-06-04 17:50:22 +08:00
|
|
|
return NewJinaModel(baseURL, j.baseModel.URLSuffix)
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (j *JinaModel) Name() string {
|
|
|
|
|
return "jina"
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:54:11 +08:00
|
|
|
// JinaEmbeddingResponse mirrors Jina's embeddings response. Embeddings is
|
|
|
|
|
// populated by multivector models such as jina-embeddings-v4.
|
|
|
|
|
type JinaEmbeddingResponse struct {
|
|
|
|
|
ID string `json:"id"`
|
|
|
|
|
Object string `json:"object"`
|
|
|
|
|
Model string `json:"model"`
|
|
|
|
|
Data []struct {
|
|
|
|
|
Object string `json:"object"`
|
|
|
|
|
Embedding []float64 `json:"embedding"`
|
|
|
|
|
Embeddings [][]float64 `json:"embeddings"`
|
|
|
|
|
Index int `json:"index"`
|
|
|
|
|
} `json:"data"`
|
|
|
|
|
Usage struct {
|
|
|
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
|
|
|
TotalTokens int `json:"total_tokens"`
|
|
|
|
|
} `json:"usage"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// JinaRerankResponse mirrors Jina's rerank response.
|
|
|
|
|
type JinaRerankResponse struct {
|
|
|
|
|
ID string `json:"id"`
|
|
|
|
|
Model string `json:"model"`
|
|
|
|
|
Results []struct {
|
|
|
|
|
Index int `json:"index"`
|
|
|
|
|
Document struct {
|
|
|
|
|
Text string `json:"text"`
|
|
|
|
|
} `json:"document"`
|
|
|
|
|
RelevanceScore float64 `json:"relevance_score"`
|
|
|
|
|
} `json:"results"`
|
|
|
|
|
Usage struct {
|
|
|
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
|
|
|
TotalTokens int `json:"total_tokens"`
|
|
|
|
|
} `json:"usage"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) ChatWithMessages(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage) (*ChatResponse, error) {
|
2026-06-04 17:50:22 +08:00
|
|
|
if err := j.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
|
|
|
return nil, err
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
}
|
|
|
|
|
if modelName == "" {
|
|
|
|
|
return nil, fmt.Errorf("model name is required")
|
|
|
|
|
}
|
|
|
|
|
if len(messages) == 0 {
|
|
|
|
|
return nil, fmt.Errorf("messages is empty")
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
baseURL, err := j.baseModel.GetBaseURL(apiConfig)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-06-04 17:50:22 +08:00
|
|
|
baseURL = strings.TrimSuffix(baseURL, "/")
|
|
|
|
|
url := fmt.Sprintf("%s/%s", baseURL, j.baseModel.URLSuffix.Chat)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
|
2026-07-23 19:12:58 +08:00
|
|
|
reqBody := buildRequestBody(chatModelConfig, modelName, messages, false)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
if chatModelConfig != nil {
|
|
|
|
|
if chatModelConfig.Thinking != nil {
|
|
|
|
|
reqBody["enable_thinking"] = *chatModelConfig.Thinking
|
|
|
|
|
}
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
}
|
|
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
body, err := j.baseModel.doRequest(ctx, url, apiConfig, reqBody, nonStreamCallTimeout)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
if err != nil {
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
return nil, err
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
}
|
|
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
return HandleNonStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig)
|
|
|
|
|
}
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
func (j *JinaModel) ChatStreamlyWithSender(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
|
|
|
|
if err := j.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
if modelName == "" {
|
|
|
|
|
return fmt.Errorf("model name is required")
|
|
|
|
|
}
|
|
|
|
|
if len(messages) == 0 {
|
|
|
|
|
return fmt.Errorf("messages is empty")
|
|
|
|
|
}
|
|
|
|
|
if err := validateStreamConfig(chatModelConfig); err != nil {
|
|
|
|
|
return err
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
}
|
|
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
baseURL, err := j.baseModel.GetBaseURL(apiConfig)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
if err != nil {
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
return err
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
}
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
baseURL = strings.TrimSuffix(baseURL, "/")
|
|
|
|
|
url := fmt.Sprintf("%s/%s", baseURL, j.baseModel.URLSuffix.Chat)
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
reqBody := buildRequestBody(chatModelConfig, modelName, messages, true)
|
|
|
|
|
reqBody["stream_options"] = map[string]interface{}{"include_usage": true}
|
Go: add Jina chat completions support (#14935)
### What problem does this PR solve?
This PR adds non-streaming chat support for the Jina Go model provider.
The Jina provider was added with embedding, rerank, model listing, and
connection checking, but `ChatWithMessages` still returned a
not-implemented error even though Jina exposes an OpenAI-compatible
`/v1/chat/completions` endpoint.
Closes #14933
**The following functionalities are now supported:**
### **Jina:**
- [x] Chat
- [ ] Stream Chat
- [x] Embedding
- [x] Rerank
- [x] Model listing
- [x] Provider connection checking
- [ ] Balance
### **Implementation details:**
- Implements `JinaModel.ChatWithMessages`
- Sends `Authorization: Bearer <api-key>` and JSON chat completion
requests
- Validates API key, model name, messages, and configured region before
making requests
- Forwards supported chat config fields: `max_tokens`, `temperature`,
`top_p`, and `stop`
- Parses the first chat completion choice into `ChatResponse.Answer`
- Adds `jina-ai/jina-vlm` as a chat-capable model in
`conf/models/jina.json`
- Adds focused unit tests for request construction, auth, response
parsing, validation errors, provider errors, and region handling
**Verification:**
```plaintext
docker run --rm -v $PWD:/repo -w /repo golang:1.25 sh -c '/usr/local/go/bin/gofmt -w internal/entity/models/jina.go internal/entity/models/jina_test.go && /usr/local/go/bin/go test -vet=off ./internal/entity/models -run TestJina -count=1'
ok ragflow/internal/entity/models 0.037s
```
Note: `go test ./internal/entity/models -run TestJina -count=1`
currently hits unrelated existing vet findings in other provider files,
so the focused Jina tests were run with `-vet=off`.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: Jin Hai <haijin.chn@gmail.com>
2026-05-17 18:03:12 -10:00
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
if chatModelConfig != nil {
|
|
|
|
|
chatModelConfig.ToolCallsResult = nil
|
|
|
|
|
chatModelConfig.UsageResult = nil
|
|
|
|
|
if chatModelConfig.Thinking != nil {
|
|
|
|
|
reqBody["enable_thinking"] = *chatModelConfig.Thinking
|
2026-07-29 18:54:11 +08:00
|
|
|
}
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
}
|
2026-07-29 18:54:11 +08:00
|
|
|
|
feat(go-models): migrate batch 2 model drivers to unified handlers (#17697)
## Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`,
`huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`,
`localai`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in #17634.
- Cut ~150 lines per driver (1398 lines removed, 155 added across 10
files).
- `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required
by the unified handler infrastructure.
- All other drivers: pure deduplication of HTTP plumbing.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthoric.com>
2026-08-03 13:54:35 +08:00
|
|
|
return j.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, func(body io.ReadCloser) error {
|
|
|
|
|
return HandleStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig, sender)
|
2026-07-29 18:54:11 +08:00
|
|
|
})
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) Embed(ctx context.Context, modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) {
|
2026-06-04 17:50:22 +08:00
|
|
|
if err := j.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 18:03:05 +08:00
|
|
|
if len(texts) == 0 {
|
|
|
|
|
return []EmbeddingData{}, nil
|
|
|
|
|
}
|
2026-07-29 18:54:11 +08:00
|
|
|
if modelName == nil || strings.TrimSpace(*modelName) == "" {
|
|
|
|
|
return nil, fmt.Errorf("model name is required")
|
|
|
|
|
}
|
2026-05-12 18:03:05 +08:00
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resolvedBaseURL, err := j.baseModel.GetBaseURL(apiConfig)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
2026-06-04 17:50:22 +08:00
|
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, j.baseModel.URLSuffix.Embedding)
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:54:11 +08:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
|
2026-05-12 18:03:05 +08:00
|
|
|
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))
|
|
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resp, err := j.baseModel.httpClient.Do(req)
|
2026-05-12 18:03:05 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to send request: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read response: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
|
return nil, fmt.Errorf("Jina embedding API error: status %d, body: %s", resp.StatusCode, string(body))
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:54:11 +08:00
|
|
|
var parsedResponse JinaEmbeddingResponse
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
if err = json.Unmarshal(body, &parsedResponse); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(parsedResponse.Data) == 0 {
|
|
|
|
|
return nil, fmt.Errorf("Jina embedding response contains no data: %s", string(body))
|
|
|
|
|
}
|
2026-07-29 18:54:11 +08:00
|
|
|
recordResponseUsage(modelUsage, parsedResponse.ID, &TokenUsage{
|
|
|
|
|
PromptTokens: parsedResponse.Usage.PromptTokens,
|
|
|
|
|
TotalTokens: parsedResponse.Usage.TotalTokens,
|
|
|
|
|
}, "embedding")
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
var embeddings []EmbeddingData
|
|
|
|
|
for _, dataElem := range parsedResponse.Data {
|
2026-07-29 18:54:11 +08:00
|
|
|
embedding := dataElem.Embedding
|
|
|
|
|
if len(embedding) == 0 && len(dataElem.Embeddings) > 0 {
|
|
|
|
|
dimensions := len(dataElem.Embeddings[0])
|
|
|
|
|
if dimensions == 0 {
|
|
|
|
|
return nil, fmt.Errorf("Jina embedding response contains an empty multivector at index %d", dataElem.Index)
|
|
|
|
|
}
|
|
|
|
|
embedding = make([]float64, dimensions)
|
|
|
|
|
for _, vector := range dataElem.Embeddings {
|
|
|
|
|
if len(vector) != dimensions {
|
|
|
|
|
return nil, fmt.Errorf("Jina embedding response contains inconsistent multivector dimensions at index %d", dataElem.Index)
|
|
|
|
|
}
|
|
|
|
|
for i, value := range vector {
|
|
|
|
|
embedding[i] += value
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for i := range embedding {
|
|
|
|
|
embedding[i] /= float64(len(dataElem.Embeddings))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if len(embedding) == 0 {
|
|
|
|
|
return nil, fmt.Errorf("Jina embedding response contains an empty vector at index %d", dataElem.Index)
|
|
|
|
|
}
|
2026-05-12 18:03:05 +08:00
|
|
|
embeddings = append(embeddings, EmbeddingData{
|
2026-07-29 18:54:11 +08:00
|
|
|
Embedding: embedding,
|
2026-05-12 18:03:05 +08:00
|
|
|
Index: dataElem.Index,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return embeddings, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) Rerank(ctx context.Context, modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig, modelUsage *common.ModelUsage) (*RerankResponse, error) {
|
2026-06-04 17:50:22 +08:00
|
|
|
if err := j.baseModel.APIConfigCheck(apiConfig); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 18:03:05 +08:00
|
|
|
if len(documents) == 0 {
|
|
|
|
|
return &RerankResponse{}, nil
|
|
|
|
|
}
|
2026-07-29 18:54:11 +08:00
|
|
|
if modelName == nil || strings.TrimSpace(*modelName) == "" {
|
|
|
|
|
return nil, fmt.Errorf("model name is required")
|
|
|
|
|
}
|
2026-05-12 18:03:05 +08:00
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resolvedBaseURL, err := j.baseModel.GetBaseURL(apiConfig)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
2026-06-04 17:50:22 +08:00
|
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, j.baseModel.URLSuffix.Rerank)
|
2026-05-12 18:03:05 +08:00
|
|
|
|
2026-07-24 10:53:09 +08:00
|
|
|
topN := len(documents)
|
|
|
|
|
if rerankConfig != nil && rerankConfig.TopN > 0 && rerankConfig.TopN < topN {
|
2026-05-12 18:03:05 +08:00
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:54:11 +08:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
|
2026-05-12 18:03:05 +08:00
|
|
|
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))
|
|
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resp, err := j.baseModel.httpClient.Do(req)
|
2026-05-12 18:03:05 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to send request: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read response: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
|
return nil, fmt.Errorf("Jina Rerank API error: status %d, body: %s", resp.StatusCode, string(body))
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:54:11 +08:00
|
|
|
var rerankResp JinaRerankResponse
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
if err = json.Unmarshal(body, &rerankResp); err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to decode response: %w", err)
|
|
|
|
|
}
|
2026-07-29 18:54:11 +08:00
|
|
|
recordResponseUsage(modelUsage, rerankResp.ID, &TokenUsage{
|
|
|
|
|
PromptTokens: rerankResp.Usage.PromptTokens,
|
|
|
|
|
TotalTokens: rerankResp.Usage.TotalTokens,
|
|
|
|
|
}, "rerank")
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
var rerankResponse RerankResponse
|
|
|
|
|
for _, result := range rerankResp.Results {
|
|
|
|
|
rerankResult := RerankResult{
|
|
|
|
|
Index: result.Index,
|
|
|
|
|
RelevanceScore: result.RelevanceScore,
|
|
|
|
|
}
|
|
|
|
|
rerankResponse.Data = append(rerankResponse.Data, rerankResult)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &rerankResponse, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) ListModels(ctx context.Context, apiConfig *APIConfig) ([]ListModelResponse, error) {
|
2026-05-12 18:03:05 +08:00
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resolvedBaseURL, err := j.baseModel.GetBaseURL(apiConfig)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
url := fmt.Sprintf("%s/%s", resolvedBaseURL, j.baseModel.URLSuffix.Models)
|
2026-05-12 18:03:05 +08:00
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
|
2026-06-04 17:50:22 +08:00
|
|
|
resp, err := j.baseModel.httpClient.Do(req)
|
2026-05-12 18:03:05 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to send request: %w", err)
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, fmt.Errorf("failed to read response body: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
|
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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{}
|
2026-07-20 10:50:53 +08:00
|
|
|
models := make([]ModelListItem, 0, len(result["data"].([]interface{})))
|
2026-05-12 18:03:05 +08:00
|
|
|
for _, model := range result["data"].([]interface{}) {
|
2026-08-03 18:07:55 +08:00
|
|
|
modelName := model.(map[string]interface{})["id"].(string)
|
2026-07-20 10:50:53 +08:00
|
|
|
models = append(models, ModelListItem{
|
2026-06-11 13:32:50 +08:00
|
|
|
ID: modelName,
|
|
|
|
|
OwnedBy: "",
|
|
|
|
|
})
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
2026-06-11 13:32:50 +08:00
|
|
|
// Jina list models: `Jina AI: Jina Embeddings v5 Text Nano`
|
|
|
|
|
return ParseListModel(ModelList{Models: models}), nil
|
2026-05-12 18:03:05 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) Balance(ctx context.Context, apiConfig *APIConfig) (map[string]interface{}, error) {
|
2026-05-12 18:03:05 +08:00
|
|
|
return nil, fmt.Errorf("no such method")
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) CheckConnection(ctx context.Context, apiConfig *APIConfig) error {
|
|
|
|
|
_, err := j.ListModels(ctx, apiConfig)
|
2026-05-12 18:03:05 +08:00
|
|
|
return err
|
|
|
|
|
}
|
2026-05-12 19:44:01 +08:00
|
|
|
|
|
|
|
|
// TranscribeAudio transcribe audio
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) TranscribeAudio(ctx context.Context, modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, modelUsage *common.ModelUsage) (*ASRResponse, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-12 19:44:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) TranscribeAudioWithSender(ctx context.Context, modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
2026-06-03 14:09:07 +08:00
|
|
|
return fmt.Errorf("%s, no such method", j.Name())
|
2026-05-12 19:44:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-15 18:41:43 +08:00
|
|
|
// AudioSpeech convert text to audio
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) AudioSpeech(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage) (*TTSResponse, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-12 19:44:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) AudioSpeechWithSender(ctx context.Context, modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
|
2026-06-03 14:09:07 +08:00
|
|
|
return fmt.Errorf("%s, no such method", j.Name())
|
2026-05-12 19:44:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// OCRFile OCR file
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) OCRFile(ctx context.Context, modelName *string, content []byte, url *string, apiConfig *APIConfig, ocrConfig *OCRConfig, modelUsage *common.ModelUsage) (*OCRFileResponse, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-15 12:29:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ParseFile parse file
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) ParseFile(ctx context.Context, modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig, modelUsage *common.ModelUsage) (*ParseFileResponse, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-15 12:29:52 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) ListTasks(ctx context.Context, apiConfig *APIConfig) ([]ListTaskStatus, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-15 12:29:52 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 22:30:57 +08:00
|
|
|
func (j *JinaModel) ShowTask(ctx context.Context, taskID string, apiConfig *APIConfig) (*TaskResponse, error) {
|
2026-06-03 14:09:07 +08:00
|
|
|
return nil, fmt.Errorf("%s, no such method", j.Name())
|
2026-05-12 19:44:01 +08:00
|
|
|
}
|