feat: 新增对多家平台的模型适配
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// AliyunMultimodalEmbeddingEndpoint 阿里云 DashScope 多模态 Embedding API 端点
|
||||
AliyunMultimodalEmbeddingEndpoint = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
|
||||
)
|
||||
|
||||
// AliyunEmbedder implements text vectorization using Aliyun DashScope multimodal embedding API
|
||||
type AliyunEmbedder struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
modelName string
|
||||
truncatePromptTokens int
|
||||
dimensions int
|
||||
modelID string
|
||||
httpClient *http.Client
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// AliyunEmbedRequest represents an Aliyun DashScope multimodal embedding request
|
||||
type AliyunEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input AliyunEmbedInput `json:"input"`
|
||||
}
|
||||
|
||||
// AliyunEmbedInput represents the input structure for Aliyun embedding
|
||||
type AliyunEmbedInput struct {
|
||||
Contents []AliyunContent `json:"contents"`
|
||||
}
|
||||
|
||||
// AliyunContent represents a single content item in the input
|
||||
type AliyunContent struct {
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// AliyunEmbedResponse represents an Aliyun DashScope embedding response
|
||||
type AliyunEmbedResponse struct {
|
||||
Output struct {
|
||||
Embeddings []struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
TextIndex int `json:"text_index"`
|
||||
} `json:"embeddings"`
|
||||
} `json:"output"`
|
||||
Usage struct {
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// AliyunErrorResponse represents an error response from Aliyun DashScope
|
||||
type AliyunErrorResponse struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// NewAliyunEmbedder creates a new Aliyun DashScope embedder
|
||||
func NewAliyunEmbedder(apiKey, baseURL, modelName string,
|
||||
truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,
|
||||
) (*AliyunEmbedder, error) {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://dashscope.aliyuncs.com"
|
||||
}
|
||||
|
||||
// Remove trailing slash and any existing path suffix
|
||||
baseURL = strings.TrimRight(baseURL, "/")
|
||||
// If baseURL contains /compatible-mode/v1, strip it for multimodal API
|
||||
if strings.Contains(baseURL, "/compatible-mode/v1") {
|
||||
baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1)
|
||||
}
|
||||
|
||||
if modelName == "" {
|
||||
return nil, fmt.Errorf("model name is required")
|
||||
}
|
||||
|
||||
if truncatePromptTokens == 0 {
|
||||
truncatePromptTokens = 511
|
||||
}
|
||||
|
||||
timeout := 60 * time.Second
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return &AliyunEmbedder{
|
||||
apiKey: apiKey,
|
||||
baseURL: baseURL,
|
||||
modelName: modelName,
|
||||
httpClient: client,
|
||||
truncatePromptTokens: truncatePromptTokens,
|
||||
EmbedderPooler: pooler,
|
||||
dimensions: dimensions,
|
||||
modelID: modelID,
|
||||
timeout: timeout,
|
||||
maxRetries: 3,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed converts text to vector
|
||||
func (e *AliyunEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
for range 3 {
|
||||
embeddings, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(embeddings) > 0 {
|
||||
return embeddings[0], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no embedding returned")
|
||||
}
|
||||
|
||||
func (e *AliyunEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
url := e.baseURL + AliyunMultimodalEmbeddingEndpoint
|
||||
|
||||
for i := 0; i <= e.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
backoffTime := time.Duration(1<<uint(i-1)) * time.Second
|
||||
if backoffTime > 10*time.Second {
|
||||
backoffTime = 10 * time.Second
|
||||
}
|
||||
logger.GetLogger(ctx).
|
||||
Infof("AliyunEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)
|
||||
|
||||
select {
|
||||
case <-time.After(backoffTime):
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder failed to create request: %v", err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+e.apiKey)
|
||||
|
||||
resp, err = e.httpClient.Do(req)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (e *AliyunEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
// Build contents array from texts
|
||||
contents := make([]AliyunContent, 0, len(texts))
|
||||
for _, text := range texts {
|
||||
contents = append(contents, AliyunContent{Text: text})
|
||||
}
|
||||
|
||||
// Create request body
|
||||
reqBody := AliyunEmbedRequest{
|
||||
Model: e.modelName,
|
||||
Input: AliyunEmbedInput{
|
||||
Contents: contents,
|
||||
},
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed marshal request error: %v", err)
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := e.doRequestWithRetry(ctx, jsonData)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed send request error: %v", err)
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed read response error: %v", err)
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// Try to parse error response
|
||||
var errResp AliyunErrorResponse
|
||||
if json.Unmarshal(body, &errResp) == nil && errResp.Message != "" {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed API error: %s - %s", errResp.Code, errResp.Message)
|
||||
return nil, fmt.Errorf("API error: %s - %s", errResp.Code, errResp.Message)
|
||||
}
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed API error: Http Status %s", resp.Status)
|
||||
return nil, fmt.Errorf("BatchEmbed API error: Http Status %s", resp.Status)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var response AliyunEmbedResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("AliyunEmbedder BatchEmbed unmarshal response error: %v", err)
|
||||
return nil, fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
// Extract embedding vectors, preserving order by text_index
|
||||
embeddings := make([][]float32, len(texts))
|
||||
for _, emb := range response.Output.Embeddings {
|
||||
if emb.TextIndex >= 0 && emb.TextIndex < len(embeddings) {
|
||||
embeddings[emb.TextIndex] = emb.Embedding
|
||||
}
|
||||
}
|
||||
|
||||
return embeddings, nil
|
||||
}
|
||||
|
||||
// GetModelName returns the model name
|
||||
func (e *AliyunEmbedder) GetModelName() string {
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
func (e *AliyunEmbedder) GetDimensions() int {
|
||||
return e.dimensions
|
||||
}
|
||||
|
||||
// GetModelID returns the model ID
|
||||
func (e *AliyunEmbedder) GetModelID() string {
|
||||
return e.modelID
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/provider"
|
||||
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
|
||||
"github.com/Tencent/WeKnora/internal/runtime"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -46,6 +47,7 @@ type Config struct {
|
||||
TruncatePromptTokens int `json:"truncate_prompt_tokens"`
|
||||
Dimensions int `json:"dimensions"`
|
||||
ModelID string `json:"model_id"`
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
|
||||
// NewEmbedder creates an embedder based on the configuration
|
||||
@@ -60,16 +62,94 @@ func NewEmbedder(config Config) (Embedder, error) {
|
||||
})
|
||||
return embedder, err
|
||||
case string(types.ModelSourceRemote):
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewOpenAIEmbedder(config.APIKey,
|
||||
config.BaseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
return embedder, err
|
||||
// Detect or use configured provider for routing
|
||||
providerName := provider.ProviderName(config.Provider)
|
||||
if providerName == "" {
|
||||
providerName = provider.DetectProvider(config.BaseURL)
|
||||
}
|
||||
|
||||
// Route to provider-specific embedders
|
||||
switch providerName {
|
||||
case provider.ProviderAliyun:
|
||||
// 检查是否是多模态嵌入模型
|
||||
// 多模态模型: tongyi-embedding-vision-*, multimodal-embedding-*
|
||||
// tex-only模型: text-embedding-v1/v2/v3/v4 应该使用 OpenAI 兼容接口,否则响应格式不匹配、embedding 返回空数组
|
||||
isMultimodalModel := strings.Contains(strings.ToLower(config.ModelName), "vision") ||
|
||||
strings.Contains(strings.ToLower(config.ModelName), "multimodal")
|
||||
|
||||
if isMultimodalModel {
|
||||
// 多模态模型需要使用DashScope专用 API 端点
|
||||
// 如果用户填写了 OpenAI 兼容模式的 URL,自动修正为多模态 API 的baseURL
|
||||
baseURL := config.BaseURL
|
||||
if baseURL == "" {
|
||||
baseURL = "https://dashscope.aliyuncs.com"
|
||||
} else if strings.Contains(baseURL, "/compatible-mode/") {
|
||||
// 移除 compatible-mode 路径,AliyunEmbedder 会自动添加多模态端点
|
||||
baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1)
|
||||
baseURL = strings.Replace(baseURL, "/compatible-mode", "", 1)
|
||||
}
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewAliyunEmbedder(config.APIKey,
|
||||
baseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
} else {
|
||||
baseURL := config.BaseURL
|
||||
if baseURL == "" || !strings.Contains(baseURL, "/compatible-mode/") {
|
||||
baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
|
||||
}
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewOpenAIEmbedder(config.APIKey,
|
||||
baseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
}
|
||||
return embedder, err
|
||||
case provider.ProviderVolcengine:
|
||||
// Volcengine Ark uses multimodal embedding API
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewVolcengineEmbedder(config.APIKey,
|
||||
config.BaseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
return embedder, err
|
||||
case provider.ProviderJina:
|
||||
// Jina AI uses different API format (truncate instead of truncate_prompt_tokens)
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewJinaEmbedder(config.APIKey,
|
||||
config.BaseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
return embedder, err
|
||||
default:
|
||||
// Use OpenAI-compatible embedder for other providers
|
||||
runtime.GetContainer().Invoke(func(pooler EmbedderPooler) {
|
||||
embedder, err = NewOpenAIEmbedder(config.APIKey,
|
||||
config.BaseURL,
|
||||
config.ModelName,
|
||||
config.TruncatePromptTokens,
|
||||
config.Dimensions,
|
||||
config.ModelID,
|
||||
pooler)
|
||||
})
|
||||
return embedder, err
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported embedder source: %s", config.Source)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// JinaEmbedder implements text vectorization functionality using Jina AI API
|
||||
// Jina API is mostly OpenAI-compatible but does NOT support truncate_prompt_tokens
|
||||
type JinaEmbedder struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
modelName string
|
||||
dimensions int
|
||||
modelID string
|
||||
httpClient *http.Client
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// JinaEmbedRequest represents a Jina embedding request
|
||||
// Note: Jina uses 'truncate' (boolean) instead of 'truncate_prompt_tokens' (integer)
|
||||
type JinaEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input []string `json:"input"`
|
||||
Truncate bool `json:"truncate,omitempty"` // Whether to truncate text exceeding max token length
|
||||
Dimensions int `json:"dimensions,omitempty"` // Output embedding dimensions (for models that support it)
|
||||
}
|
||||
|
||||
// JinaEmbedResponse represents a Jina embedding response
|
||||
type JinaEmbedResponse struct {
|
||||
Data []struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
Index int `json:"index"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// NewJinaEmbedder creates a new Jina embedder
|
||||
func NewJinaEmbedder(apiKey, baseURL, modelName string,
|
||||
truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,
|
||||
) (*JinaEmbedder, error) {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://api.jina.ai/v1"
|
||||
}
|
||||
|
||||
if modelName == "" {
|
||||
return nil, fmt.Errorf("model name is required")
|
||||
}
|
||||
|
||||
timeout := 60 * time.Second
|
||||
|
||||
// Create HTTP client
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return &JinaEmbedder{
|
||||
apiKey: apiKey,
|
||||
baseURL: baseURL,
|
||||
modelName: modelName,
|
||||
httpClient: client,
|
||||
EmbedderPooler: pooler,
|
||||
dimensions: dimensions,
|
||||
modelID: modelID,
|
||||
timeout: timeout,
|
||||
maxRetries: 3,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed converts text to vector
|
||||
func (e *JinaEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
for range 3 {
|
||||
embeddings, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(embeddings) > 0 {
|
||||
return embeddings[0], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no embedding returned")
|
||||
}
|
||||
|
||||
func (e *JinaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
url := e.baseURL + "/embeddings"
|
||||
|
||||
for i := 0; i <= e.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
backoffTime := time.Duration(1<<uint(i-1)) * time.Second
|
||||
if backoffTime > 10*time.Second {
|
||||
backoffTime = 10 * time.Second
|
||||
}
|
||||
logger.GetLogger(ctx).
|
||||
Infof("JinaEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)
|
||||
|
||||
select {
|
||||
case <-time.After(backoffTime):
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild request each time to ensure Body is valid
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder failed to create request: %v", err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+e.apiKey)
|
||||
|
||||
resp, err = e.httpClient.Do(req)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (e *JinaEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
// Create request body - Jina uses 'truncate' boolean instead of 'truncate_prompt_tokens'
|
||||
reqBody := JinaEmbedRequest{
|
||||
Model: e.modelName,
|
||||
Input: texts,
|
||||
Truncate: true, // Enable truncation for long texts
|
||||
}
|
||||
|
||||
// Only include dimensions if specified and greater than 0
|
||||
if e.dimensions > 0 {
|
||||
reqBody.Dimensions = e.dimensions
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch marshal request error: %v", err)
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
|
||||
// Send request
|
||||
resp, err := e.doRequestWithRetry(ctx, jsonData)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch send request error: %v", err)
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
if resp.Body != nil {
|
||||
defer resp.Body.Close()
|
||||
}
|
||||
|
||||
// Read response
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch read response error: %v", err)
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch API error: Http Status %s, Body: %s", resp.Status, string(body))
|
||||
return nil, fmt.Errorf("EmbedBatch API error: Http Status %s", resp.Status)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var response JinaEmbedResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("JinaEmbedder EmbedBatch unmarshal response error: %v", err)
|
||||
return nil, fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
// Extract embedding vectors
|
||||
embeddings := make([][]float32, 0, len(response.Data))
|
||||
for _, data := range response.Data {
|
||||
embeddings = append(embeddings, data.Embedding)
|
||||
}
|
||||
|
||||
return embeddings, nil
|
||||
}
|
||||
|
||||
// GetModelName returns the model name
|
||||
func (e *JinaEmbedder) GetModelName() string {
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
func (e *JinaEmbedder) GetDimensions() int {
|
||||
return e.dimensions
|
||||
}
|
||||
|
||||
// GetModelID returns the model ID
|
||||
func (e *JinaEmbedder) GetModelID() string {
|
||||
return e.modelID
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package embedding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// VolcengineMultimodalEmbeddingPath 火山引擎 Ark 多模态 Embedding API 路径
|
||||
VolcengineMultimodalEmbeddingPath = "/api/v3/embeddings/multimodal"
|
||||
)
|
||||
|
||||
// VolcengineEmbedder implements text vectorization using Volcengine Ark multimodal embedding API
|
||||
type VolcengineEmbedder struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
modelName string
|
||||
truncatePromptTokens int
|
||||
dimensions int
|
||||
modelID string
|
||||
httpClient *http.Client
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
EmbedderPooler
|
||||
}
|
||||
|
||||
// VolcengineEmbedRequest represents a Volcengine Ark multimodal embedding request
|
||||
type VolcengineEmbedRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input []VolcengineInputContent `json:"input"`
|
||||
}
|
||||
|
||||
// VolcengineInputContent represents a single input item for Volcengine
|
||||
type VolcengineInputContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *VolcengineImageURL `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
// VolcengineImageURL represents the image URL structure for Volcengine
|
||||
type VolcengineImageURL struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// VolcengineEmbedResponse represents a Volcengine Ark multimodal embedding response
|
||||
// Multimodal API returns data as an object with embedding array directly
|
||||
type VolcengineEmbedResponse struct {
|
||||
Object string `json:"object"`
|
||||
Data struct {
|
||||
Embedding []float32 `json:"embedding"`
|
||||
} `json:"data"`
|
||||
Model string `json:"model"`
|
||||
Usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
// VolcengineErrorResponse represents an error response from Volcengine
|
||||
type VolcengineErrorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// NewVolcengineEmbedder creates a new Volcengine Ark embedder
|
||||
func NewVolcengineEmbedder(apiKey, baseURL, modelName string,
|
||||
truncatePromptTokens int, dimensions int, modelID string, pooler EmbedderPooler,
|
||||
) (*VolcengineEmbedder, error) {
|
||||
if baseURL == "" {
|
||||
baseURL = "https://ark.cn-beijing.volces.com"
|
||||
}
|
||||
|
||||
// Remove trailing slash
|
||||
baseURL = strings.TrimRight(baseURL, "/")
|
||||
|
||||
// Extract base host if URL contains the full multimodal path
|
||||
if strings.Contains(baseURL, "/embeddings/multimodal") {
|
||||
// Strip the path to get base URL
|
||||
if idx := strings.Index(baseURL, "/api/"); idx != -1 {
|
||||
baseURL = baseURL[:idx]
|
||||
}
|
||||
} else if strings.HasSuffix(baseURL, "/api/v3") {
|
||||
// If it ends with /api/v3, keep just the host
|
||||
baseURL = strings.TrimSuffix(baseURL, "/api/v3")
|
||||
}
|
||||
|
||||
if modelName == "" {
|
||||
return nil, fmt.Errorf("model name is required")
|
||||
}
|
||||
|
||||
if truncatePromptTokens == 0 {
|
||||
truncatePromptTokens = 511
|
||||
}
|
||||
|
||||
timeout := 60 * time.Second
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return &VolcengineEmbedder{
|
||||
apiKey: apiKey,
|
||||
baseURL: baseURL,
|
||||
modelName: modelName,
|
||||
httpClient: client,
|
||||
truncatePromptTokens: truncatePromptTokens,
|
||||
EmbedderPooler: pooler,
|
||||
dimensions: dimensions,
|
||||
modelID: modelID,
|
||||
timeout: timeout,
|
||||
maxRetries: 3,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed converts text to vector
|
||||
func (e *VolcengineEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
|
||||
for range 3 {
|
||||
embeddings, err := e.BatchEmbed(ctx, []string{text})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(embeddings) > 0 {
|
||||
return embeddings[0], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no embedding returned")
|
||||
}
|
||||
|
||||
func (e *VolcengineEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
url := e.baseURL + VolcengineMultimodalEmbeddingPath
|
||||
|
||||
for i := 0; i <= e.maxRetries; i++ {
|
||||
if i > 0 {
|
||||
backoffTime := time.Duration(1<<uint(i-1)) * time.Second
|
||||
if backoffTime > 10*time.Second {
|
||||
backoffTime = 10 * time.Second
|
||||
}
|
||||
logger.GetLogger(ctx).
|
||||
Infof("VolcengineEmbedder retrying request (%d/%d), waiting %v", i, e.maxRetries, backoffTime)
|
||||
|
||||
select {
|
||||
case <-time.After(backoffTime):
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder failed to create request: %v", err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+e.apiKey)
|
||||
|
||||
resp, err = e.httpClient.Do(req)
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder request failed (attempt %d/%d): %v", i+1, e.maxRetries+1, err)
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (e *VolcengineEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
|
||||
embeddings := make([][]float32, len(texts))
|
||||
|
||||
// Volcengine multimodal API returns a single combined embedding for all inputs,
|
||||
// so we need to call the API once per text for proper batch embedding
|
||||
for i, text := range texts {
|
||||
input := []VolcengineInputContent{
|
||||
{
|
||||
Type: "text",
|
||||
Text: text,
|
||||
},
|
||||
}
|
||||
|
||||
reqBody := VolcengineEmbedRequest{
|
||||
Model: e.modelName,
|
||||
Input: input,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed marshal request error: %v", err)
|
||||
return nil, fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := e.doRequestWithRetry(ctx, jsonData)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed send request error: %v", err)
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed read response error: %v", err)
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errResp VolcengineErrorResponse
|
||||
if json.Unmarshal(body, &errResp) == nil && errResp.Error.Message != "" {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed API error: %s - %s", errResp.Error.Code, errResp.Error.Message)
|
||||
return nil, fmt.Errorf("API error: %s - %s", errResp.Error.Code, errResp.Error.Message)
|
||||
}
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed API error: Http Status %s", resp.Status)
|
||||
return nil, fmt.Errorf("BatchEmbed API error: Http Status %s", resp.Status)
|
||||
}
|
||||
|
||||
var response VolcengineEmbedResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("VolcengineEmbedder BatchEmbed unmarshal response error: %v", err)
|
||||
return nil, fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
|
||||
embeddings[i] = response.Data.Embedding
|
||||
}
|
||||
|
||||
return embeddings, nil
|
||||
|
||||
}
|
||||
|
||||
// GetModelName returns the model name
|
||||
func (e *VolcengineEmbedder) GetModelName() string {
|
||||
return e.modelName
|
||||
}
|
||||
|
||||
// GetDimensions returns the vector dimensions
|
||||
func (e *VolcengineEmbedder) GetDimensions() int {
|
||||
return e.dimensions
|
||||
}
|
||||
|
||||
// GetModelID returns the model ID
|
||||
func (e *VolcengineEmbedder) GetModelID() string {
|
||||
return e.modelID
|
||||
}
|
||||
Reference in New Issue
Block a user