feat(models): support custom HTTP headers across all remote model calls

Introduce per-model `custom_headers` config (similar to OpenAI Python SDK's
`extra_headers`) so users can inject gateway auth tokens, trace IDs, etc.
into every outbound API request for chat / embedding / rerank / VLLM / ASR
models. Reserved headers like Authorization / Content-Type are always
preserved to avoid breaking auth or signing flows.

Along the way, unify production and "test connection" paths onto a single
`ConfigFromModel(*types.Model, appID, appSecret)` constructor in each
model package. Both `service.modelService.GetXxxModel` and the four
`handler.initialization.Check*Model` / `TestEmbeddingModel` endpoints now
go through the same field mapping, so new parameters only need to be
added in one place.

Backend:
- Add `CustomHeaders map[string]string` to `types.ModelParameters` with
  JSON/YAML `omitempty` tags for forward compatibility.
- New `internal/utils/extraheaders.go` providing `ApplyCustomHeaders`
  (for hand-rolled HTTP paths) and `WrapHTTPClientWithHeaders` /
  `CustomHeadersRoundTripper` (for SDK paths like go-openai). Reserved
  headers (Authorization, api-key, Content-Type, Accept, Host,
  Content-Length, User-Agent) are filtered out.
- Inject headers in every remote model path: chat (SDK + raw HTTP),
  embedding (openai/aliyun/jina/volcengine/nvidia/azure_openai), rerank
  (remote_api/aliyun/jina/nvidia/zhipu — via shared `customHeaderSetter`
  interface), VLM and ASR (via http.Client wrapping).
- Add `ConfigFromModel` to each of chat/embedding/rerank/vlm/asr,
  consolidating field mapping (ExtraConfig, CustomHeaders, InterfaceType
  defaulting, WeKnoraCloud credentials, etc.) and cover it with
  dedicated unit tests per package.
- Refactor `service/model.go`: replace ~100 lines of hand-written Config
  literals with one-line `ConfigFromModel` calls; drop the now-unused
  `stringMapToAnyMap` helper.
- Refactor `handler/initialization.go` test-connection endpoints: merge
  four ad-hoc request structs into one `ModelTestRequest`, extract
  `buildTestModel` and `resolveTenantWeKnoraCloudCreds` helpers, and
  route all four endpoints through `ConfigFromModel` + `NewXxx` so the
  test path is now behaviorally identical to production.

Frontend:
- Add `custom_headers` to the `ModelConfig` API type.
- `ModelEditorDialog.vue`: new Key-Value header editor (add/remove rows),
  auto-converts map <-> array when loading/saving, and passes the
  current header set to the `Test Connection` button so the preview
  reflects exactly what production will send.
- `ModelSettings.vue`: serialize the header array back into a map for
  the backend (drops empty rows).
- i18n: add custom-header labels / descriptions / placeholders to
  zh-CN, en-US, ru-RU, ko-KR.

Tests:
- `internal/utils/extraheaders_test.go` covers reserved-header filtering
  and round-tripper wrapping (including nil-client fallback).
- New `config_from_model_test.go` in chat / embedding / rerank / vlm /
  asr verifies all fields (CustomHeaders, ExtraConfig, InterfaceType
  defaulting, AppID/AppSecret) are propagated end-to-end.
This commit is contained in:
wizardchen
2026-04-23 23:13:10 +08:00
committed by lyingbug
parent a6d4266c93
commit fd3e2992b1
37 changed files with 1105 additions and 334 deletions
+19
View File
@@ -36,6 +36,25 @@ type Config struct {
APIKey string
ModelID string
Language string // optional: specify language for transcription
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
}
// ConfigFromModel 根据 types.Model 构造 asr.Config。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// 当前 ASR 不涉及 WeKnoraCloud 凭证,所以签名不含 appID/appSecret。
func ConfigFromModel(m *types.Model) *Config {
if m == nil {
return nil
}
return &Config{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
CustomHeaders: m.Parameters.CustomHeaders,
}
}
// NewASR creates an ASR instance based on the provided configuration.
@@ -0,0 +1,36 @@
package asr
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "asr-1",
Name: "whisper-1",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk",
CustomHeaders: map[string]string{"X": "y"},
},
}
cfg := ConfigFromModel(m)
if cfg == nil || cfg.ModelID != "asr-1" || cfg.ModelName != "whisper-1" {
t.Fatalf("identity mismatch: %+v", cfg)
}
if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk" {
t.Errorf("connection fields mismatch: %+v", cfg)
}
if cfg.CustomHeaders["X"] != "y" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
}
func TestConfigFromModel_Nil(t *testing.T) {
if got := ConfigFromModel(nil); got != nil {
t.Fatalf("expected nil, got %+v", got)
}
}
+9 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
openai "github.com/sashabaranov/go-openai"
)
@@ -33,7 +34,14 @@ func NewOpenAIASR(config *Config) (*OpenAIASR, error) {
if config.BaseURL != "" {
apiCfg.BaseURL = config.BaseURL
}
apiCfg.HTTPClient = &http.Client{Timeout: asrDefaultTimeout}
httpClient := &http.Client{Timeout: asrDefaultTimeout}
// 注入用户自定义 HTTP header(类似 OpenAI Python SDK 的 extra_headers)
if len(config.CustomHeaders) > 0 {
apiCfg.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, config.CustomHeaders)
} else {
apiCfg.HTTPClient = httpClient
}
return &OpenAIASR{
modelName: config.ModelName,
+26 -2
View File
@@ -101,8 +101,32 @@ type ChatConfig struct {
ModelID string
Provider string
ExtraConfig map[string]string
AppID string
AppSecret string // 加密值,由工厂函数调用方传入,在 NewWeKnoraCloudChat 中使用前已解密
// CustomHeaders 允许在调用远程 OpenAI 兼容 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
AppSecret string // 加密值,由工厂函数调用方传入,在 NewWeKnoraCloudChat 中使用前已解密
}
// ConfigFromModel 根据 types.Model 构造 ChatConfig。
// 保证生产路径(service 层根据 DB 中的模型配置拉起实例)和测试路径
// (handler 层根据前端表单临时拉起实例)走完全相同的字段映射,避免重复样板。
// appID / appSecret 是已经解密/解析好的 WeKnoraCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) *ChatConfig {
if m == nil {
return nil
}
return &ChatConfig{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
// NewChat 创建聊天实例
@@ -0,0 +1,59 @@
package chat
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// TestConfigFromModel 验证 ConfigFromModel 能把 types.Model 完整映射到 ChatConfig,
// 避免后续新加字段时只在生产路径或测试路径其中一侧更新导致功能漏配。
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "model-123",
Name: "gpt-4o-mini",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "openai",
ExtraConfig: map[string]string{
"deployment": "prod",
},
CustomHeaders: map[string]string{
"X-Gateway-Token": "abc",
"X-Trace-ID": "t-1",
},
},
}
cfg := ConfigFromModel(m, "app-id", "app-secret")
if cfg == nil {
t.Fatal("ConfigFromModel returned nil")
}
if cfg.ModelID != "model-123" || cfg.ModelName != "gpt-4o-mini" {
t.Errorf("model identity not propagated: %+v", cfg)
}
if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk-xxx" {
t.Errorf("connection fields not propagated: %+v", cfg)
}
if cfg.Provider != "openai" {
t.Errorf("provider not propagated: %q", cfg.Provider)
}
if cfg.ExtraConfig["deployment"] != "prod" {
t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig)
}
if cfg.CustomHeaders["X-Gateway-Token"] != "abc" ||
cfg.CustomHeaders["X-Trace-ID"] != "t-1" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
if cfg.AppID != "app-id" || cfg.AppSecret != "app-secret" {
t.Errorf("cloud credentials not propagated: %+v", cfg)
}
}
func TestConfigFromModel_Nil(t *testing.T) {
if got := ConfigFromModel(nil, "", ""); got != nil {
t.Fatalf("expected nil for nil model, got %+v", got)
}
}
+28 -8
View File
@@ -41,6 +41,8 @@ type RemoteAPIChat struct {
provider provider.ProviderName
appID string
appSecret string
// customHeaders 为用户在模型配置中指定的自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
customHeaders map[string]string
// requestCustomizer 允许子类自定义请求
// 返回自定义请求体(如果为 nil 则使用标准请求)和是否需要使用原始 HTTP 请求
@@ -86,6 +88,17 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
}
}
// 如果指定了 CustomHeaders,则给 SDK 使用的 HTTPClient 挂一层 RoundTripper,
// 在每个请求上自动注入这些 header(raw HTTP 路径会在发送前单独处理)。
if len(chatConfig.CustomHeaders) > 0 {
if httpClient, ok := config.HTTPClient.(*http.Client); ok {
config.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, chatConfig.CustomHeaders)
} else {
// SDK 默认未显式设置时 HTTPClient 为 nil,此时构造一个新的注入了 header 的 client。
config.HTTPClient = secutils.WrapHTTPClientWithHeaders(nil, chatConfig.CustomHeaders)
}
}
modelName := chatConfig.ModelName
if chatConfig.ExtraConfig != nil {
if override := strings.TrimSpace(chatConfig.ExtraConfig["remote_model_name"]); override != "" {
@@ -102,14 +115,15 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
}
return &RemoteAPIChat{
modelName: modelName,
client: openai.NewClientWithConfig(config),
modelID: chatConfig.ModelID,
baseURL: chatConfig.BaseURL,
apiKey: apiKey,
provider: providerName,
appID: chatConfig.AppID,
appSecret: chatConfig.AppSecret,
modelName: modelName,
client: openai.NewClientWithConfig(config),
modelID: chatConfig.ModelID,
baseURL: chatConfig.BaseURL,
apiKey: apiKey,
provider: providerName,
appID: chatConfig.AppID,
appSecret: chatConfig.AppSecret,
customHeaders: chatConfig.CustomHeaders,
}, nil
}
@@ -368,6 +382,9 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
}
// 注入用户自定义 header(保留头会在工具内部自动跳过)
secutils.ApplyCustomHeaders(httpReq, c.customHeaders)
logger.Infof(ctx, "[LLM Request] Remote HTTP, endpoint=%s, model=%s",
endpoint, c.modelName)
@@ -538,6 +555,9 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint stri
}
httpReq.Header.Set("Accept", "text/event-stream")
// 注入用户自定义 header(保留头会在工具内部自动跳过)
secutils.ApplyCustomHeaders(httpReq, c.customHeaders)
resp, err := rawHTTPClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
+8
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
const (
@@ -29,9 +30,15 @@ type AliyunEmbedder struct {
httpClient *http.Client
timeout time.Duration
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (e *AliyunEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
// AliyunEmbedRequest represents an Aliyun DashScope multimodal embedding request
type AliyunEmbedRequest struct {
Model string `json:"model"`
@@ -154,6 +161,7 @@ func (e *AliyunEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// AzureOpenAIEmbedder implements text vectorization using Azure OpenAI API
@@ -24,9 +25,15 @@ type AzureOpenAIEmbedder struct {
apiVersion string
httpClient *http.Client
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (e *AzureOpenAIEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
type azureOpenAIEmbedRequest struct {
Model string `json:"model"`
Input []string `json:"input"`
@@ -157,6 +164,7 @@ func (e *AzureOpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData [
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("api-key", e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
@@ -0,0 +1,43 @@
package embedding
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "emb-1",
Name: "text-embedding-3-small",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "openai",
EmbeddingParameters: types.EmbeddingParameters{
Dimension: 1536,
TruncatePromptTokens: 512,
},
ExtraConfig: map[string]string{"region": "us-east"},
CustomHeaders: map[string]string{"X-Gateway": "g1"},
},
}
cfg := ConfigFromModel(m, "app", "secret")
if cfg.ModelID != "emb-1" || cfg.ModelName != "text-embedding-3-small" {
t.Errorf("identity mismatch: %+v", cfg)
}
if cfg.Dimensions != 1536 || cfg.TruncatePromptTokens != 512 {
t.Errorf("embedding params mismatch: %+v", cfg)
}
if cfg.CustomHeaders["X-Gateway"] != "g1" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
if cfg.ExtraConfig["region"] != "us-east" {
t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig)
}
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
t.Errorf("cloud creds mismatch: %+v", cfg)
}
}
+62 -9
View File
@@ -49,8 +49,33 @@ type Config struct {
ModelID string `json:"model_id"`
Provider string `json:"provider"`
ExtraConfig map[string]string `json:"extra_config"`
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string `json:"custom_headers"`
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
}
// ConfigFromModel 根据 types.Model 构造 embedding.Config。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) Config {
if m == nil {
return Config{}
}
return Config{
Source: m.Source,
BaseURL: m.Parameters.BaseURL,
APIKey: m.Parameters.APIKey,
ModelID: m.ID,
ModelName: m.Name,
Dimensions: m.Parameters.EmbeddingParameters.Dimension,
TruncatePromptTokens: m.Parameters.EmbeddingParameters.TruncatePromptTokens,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
// NewEmbedder creates an embedder based on the configuration
@@ -97,46 +122,62 @@ func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1)
baseURL = strings.Replace(baseURL, "/compatible-mode", "", 1)
}
embedder, err = NewAliyunEmbedder(config.APIKey,
aliyunEmb, aErr := NewAliyunEmbedder(config.APIKey,
baseURL,
config.ModelName,
config.TruncatePromptTokens,
config.Dimensions,
config.ModelID,
pooler)
if aliyunEmb != nil {
aliyunEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = aliyunEmb, aErr
} else {
baseURL := config.BaseURL
if baseURL == "" || !strings.Contains(baseURL, "/compatible-mode/") {
baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
embedder, err = NewOpenAIEmbedder(config.APIKey,
openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey,
baseURL,
config.ModelName,
config.TruncatePromptTokens,
config.Dimensions,
config.ModelID,
pooler)
if openaiEmb != nil {
openaiEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = openaiEmb, oErr
}
return embedder, err
case provider.ProviderVolcengine:
// Volcengine Ark uses multimodal embedding API
embedder, err = NewVolcengineEmbedder(config.APIKey,
volcEmb, vErr := NewVolcengineEmbedder(config.APIKey,
config.BaseURL,
config.ModelName,
config.TruncatePromptTokens,
config.Dimensions,
config.ModelID,
pooler)
if volcEmb != nil {
volcEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = volcEmb, vErr
return embedder, err
case provider.ProviderJina:
// Jina AI uses different API format (truncate instead of truncate_prompt_tokens)
embedder, err = NewJinaEmbedder(config.APIKey,
jinaEmb, jErr := NewJinaEmbedder(config.APIKey,
config.BaseURL,
config.ModelName,
config.TruncatePromptTokens,
config.Dimensions,
config.ModelID,
pooler)
if jinaEmb != nil {
jinaEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = jinaEmb, jErr
return embedder, err
case provider.ProviderAzureOpenAI:
apiVersion := "2024-10-21"
@@ -145,7 +186,7 @@ func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
apiVersion = v
}
}
embedder, err = NewAzureOpenAIEmbedder(config.APIKey,
azureEmb, azErr := NewAzureOpenAIEmbedder(config.APIKey,
config.BaseURL,
config.ModelName,
config.TruncatePromptTokens,
@@ -153,27 +194,39 @@ func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll
config.ModelID,
apiVersion,
pooler)
if azureEmb != nil {
azureEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = azureEmb, azErr
return embedder, err
case provider.ProviderNvidia:
embedder, err = NewNvidiaEmbedder(config.APIKey,
nvEmb, nErr := NewNvidiaEmbedder(config.APIKey,
config.BaseURL,
config.ModelName,
config.Dimensions,
config.ModelID,
pooler)
if nvEmb != nil {
nvEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = nvEmb, nErr
return embedder, err
case provider.ProviderWeKnoraCloud:
embedder, err = NewWeKnoraCloudEmbedder(config)
return embedder, err
default:
// Use OpenAI-compatible embedder for other providers
embedder, err = NewOpenAIEmbedder(config.APIKey,
openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey,
config.BaseURL,
config.ModelName,
config.TruncatePromptTokens,
config.Dimensions,
config.ModelID,
pooler)
if openaiEmb != nil {
openaiEmb.SetCustomHeaders(config.CustomHeaders)
}
embedder, err = openaiEmb, oErr
return embedder, err
}
default:
+16 -8
View File
@@ -10,22 +10,29 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// 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
apiKey string
baseURL string
modelName string
dimensions int
modelID string
httpClient *http.Client
timeout time.Duration
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (e *JinaEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
// JinaEmbedRequest represents a Jina embedding request
// Note: Jina uses 'truncate' (boolean) instead of 'truncate_prompt_tokens' (integer)
type JinaEmbedRequest struct {
@@ -118,6 +125,7 @@ func (e *JinaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
+16 -8
View File
@@ -11,21 +11,28 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// NvidiaEmbedder implements text vectorization functionality using NVIDIA API
type NvidiaEmbedder struct {
apiKey string
baseURL string
modelName string
dimensions int
modelID string
httpClient *http.Client
timeout time.Duration
maxRetries int
apiKey string
baseURL string
modelName string
dimensions int
modelID string
httpClient *http.Client
timeout time.Duration
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (e *NvidiaEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
// NvidiaEmbedRequest represents an NVIDIA embedding request
type NvidiaEmbedRequest struct {
Model string `json:"model"`
@@ -118,6 +125,7 @@ func (e *NvidiaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
+9
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// OpenAIEmbedder implements text vectorization functionality using OpenAI API
@@ -23,6 +24,7 @@ type OpenAIEmbedder struct {
httpClient *http.Client
timeout time.Duration
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
@@ -79,6 +81,12 @@ func NewOpenAIEmbedder(apiKey, baseURL, modelName string,
}, nil
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
// 保留头(Authorization、Content-Type 等)会在发送时被自动跳过。
func (e *OpenAIEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
// Embed converts text to vector
func (e *OpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
for range 3 {
@@ -122,6 +130,7 @@ func (e *OpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
+8
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
const (
@@ -29,9 +30,15 @@ type VolcengineEmbedder struct {
httpClient *http.Client
timeout time.Duration
maxRetries int
customHeaders map[string]string
EmbedderPooler
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (e *VolcengineEmbedder) SetCustomHeaders(headers map[string]string) {
e.customHeaders = headers
}
// VolcengineEmbedRequest represents a Volcengine Ark multimodal embedding request
type VolcengineEmbedRequest struct {
Model string `json:"model"`
@@ -165,6 +172,7 @@ func (e *VolcengineEmbedder) doRequestWithRetry(ctx context.Context, jsonData []
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+e.apiKey)
secutils.ApplyCustomHeaders(req, e.customHeaders)
resp, err = e.httpClient.Do(req)
if err == nil {
+13 -5
View File
@@ -9,15 +9,22 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// AliyunReranker implements a reranking system based on Aliyun DashScope models
type AliyunReranker struct {
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
customHeaders map[string]string
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (r *AliyunReranker) SetCustomHeaders(headers map[string]string) {
r.customHeaders = headers
}
// AliyunRerankRequest represents a request to rerank documents using Aliyun DashScope API
@@ -111,6 +118,7 @@ func (r *AliyunReranker) Rerank(ctx context.Context, query string, documents []s
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
secutils.ApplyCustomHeaders(req, r.customHeaders)
logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, r.baseURL, query, documents))
@@ -0,0 +1,32 @@
package rerank
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "rr-1",
Name: "bge-reranker-v2-m3",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "siliconflow",
ExtraConfig: map[string]string{"flag": "on"},
CustomHeaders: map[string]string{"X-Gateway": "g"},
},
}
cfg := ConfigFromModel(m, "app", "secret")
if cfg == nil || cfg.ModelID != "rr-1" || cfg.ModelName != "bge-reranker-v2-m3" {
t.Fatalf("identity mismatch: %+v", cfg)
}
if cfg.Provider != "siliconflow" || cfg.CustomHeaders["X-Gateway"] != "g" {
t.Errorf("provider/headers not propagated: %+v", cfg)
}
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
t.Errorf("cloud creds mismatch: %+v", cfg)
}
}
+13 -5
View File
@@ -9,16 +9,23 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// JinaReranker implements a reranking system using Jina AI API
// Jina API uses different parameters than standard OpenAI-compatible APIs
type JinaReranker struct {
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
customHeaders map[string]string
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (r *JinaReranker) SetCustomHeaders(headers map[string]string) {
r.customHeaders = headers
}
// JinaRerankRequest represents a Jina rerank request
@@ -79,6 +86,7 @@ func (r *JinaReranker) Rerank(ctx context.Context, query string, documents []str
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
secutils.ApplyCustomHeaders(req, r.customHeaders)
logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, fmt.Sprintf("%s/rerank", r.baseURL), query, documents))
+13 -5
View File
@@ -9,16 +9,23 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// NvidiaReranker implements a reranking system using Jina AI API
// Jina API uses different parameters than standard OpenAI-compatible APIs
type NvidiaReranker struct {
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
customHeaders map[string]string
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (r *NvidiaReranker) SetCustomHeaders(headers map[string]string) {
r.customHeaders = headers
}
type NvidiaRerankDocument struct {
Text string `json:"text"`
@@ -88,6 +95,7 @@ func (r *NvidiaReranker) Rerank(ctx context.Context, query string, documents []s
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
secutils.ApplyCustomHeaders(req, r.customHeaders)
// Log the curl equivalent for debugging (API key masked for security)
logger.GetLogger(ctx).Infof(
+13 -5
View File
@@ -9,15 +9,22 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// OpenAIReranker implements a reranking system based on OpenAI models
type OpenAIReranker struct {
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
customHeaders map[string]string
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (r *OpenAIReranker) SetCustomHeaders(headers map[string]string) {
r.customHeaders = headers
}
// RerankRequest represents a request to rerank documents based on relevance to a query
@@ -81,6 +88,7 @@ func (r *OpenAIReranker) Rerank(ctx context.Context, query string, documents []s
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
secutils.ApplyCustomHeaders(req, r.customHeaders)
logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, fmt.Sprintf("%s/rerank", r.baseURL), query, documents))
+47 -8
View File
@@ -86,8 +86,31 @@ type RerankerConfig struct {
ModelID string
Provider string // Provider identifier: openai, aliyun, zhipu, siliconflow, jina, generic
ExtraConfig map[string]string
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
AppSecret string // 加密值,工厂函数调用方传入,使用前已解密
}
// ConfigFromModel 根据 types.Model 构造 RerankerConfig。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) *RerankerConfig {
if m == nil {
return nil
}
return &RerankerConfig{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
// NewReranker creates a reranker based on the configuration
@@ -99,6 +122,11 @@ func NewReranker(config *RerankerConfig) (Reranker, error) {
return &debugReranker{inner: r}, nil
}
// customHeaderSetter 表示支持注入自定义 HTTP header 的 reranker 实现。
type customHeaderSetter interface {
SetCustomHeaders(map[string]string)
}
func newReranker(config *RerankerConfig) (Reranker, error) {
// Use provider field if set, otherwise detect from URL using provider registry
providerName := provider.ProviderName(config.Provider)
@@ -106,18 +134,29 @@ func newReranker(config *RerankerConfig) (Reranker, error) {
providerName = provider.DetectProvider(config.BaseURL)
}
var (
reranker Reranker
err error
)
switch providerName {
case provider.ProviderAliyun:
return NewAliyunReranker(config)
reranker, err = NewAliyunReranker(config)
case provider.ProviderZhipu:
return NewZhipuReranker(config)
reranker, err = NewZhipuReranker(config)
case provider.ProviderJina:
return NewJinaReranker(config)
reranker, err = NewJinaReranker(config)
case provider.ProviderNvidia:
return NewNvidiaReranker(config)
reranker, err = NewNvidiaReranker(config)
case provider.ProviderWeKnoraCloud:
return NewWeKnoraCloudReranker(config)
reranker, err = NewWeKnoraCloudReranker(config)
default:
return NewOpenAIReranker(config)
reranker, err = NewOpenAIReranker(config)
}
if err != nil {
return nil, err
}
if setter, ok := reranker.(customHeaderSetter); ok {
setter.SetCustomHeaders(config.CustomHeaders)
}
return reranker, nil
}
+13 -5
View File
@@ -9,15 +9,22 @@ import (
"net/http"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// ZhipuReranker implements a reranking system based on Zhipu AI models
type ZhipuReranker struct {
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
modelName string // Name of the model used for reranking
modelID string // Unique identifier of the model
apiKey string // API key for authentication
baseURL string // Base URL for API requests
client *http.Client // HTTP client for making API requests
customHeaders map[string]string
}
// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
func (r *ZhipuReranker) SetCustomHeaders(headers map[string]string) {
r.customHeaders = headers
}
// ZhipuRerankRequest represents a request to rerank documents using Zhipu AI API
@@ -92,6 +99,7 @@ func (r *ZhipuReranker) Rerank(ctx context.Context, query string, documents []st
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey))
secutils.ApplyCustomHeaders(req, r.customHeaders)
logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, r.baseURL, query, documents))
@@ -0,0 +1,59 @@
package vlm
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestConfigFromModel_RemoteDefaultsToOpenAI(t *testing.T) {
m := &types.Model{
ID: "v1",
Name: "gpt-4o",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk",
Provider: "openai",
ExtraConfig: map[string]string{"x": "y"},
CustomHeaders: map[string]string{"H": "v"},
},
}
cfg := ConfigFromModel(m, "app", "secret")
if cfg.InterfaceType != "openai" {
t.Errorf("expected openai default for remote, got %q", cfg.InterfaceType)
}
if cfg.CustomHeaders["H"] != "v" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
if cfg.Extra["x"] != "y" {
t.Errorf("ExtraConfig not propagated as Extra: %+v", cfg.Extra)
}
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
t.Errorf("cloud creds mismatch: %+v", cfg)
}
}
func TestConfigFromModel_LocalDefaultsToOllama(t *testing.T) {
m := &types.Model{
Name: "qwen2-vl",
Source: types.ModelSourceLocal,
}
cfg := ConfigFromModel(m, "", "")
if cfg.InterfaceType != "ollama" {
t.Errorf("expected ollama default for local, got %q", cfg.InterfaceType)
}
}
func TestConfigFromModel_RespectsExplicitInterface(t *testing.T) {
m := &types.Model{
Name: "qwen2-vl",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
InterfaceType: "ollama",
},
}
if got := ConfigFromModel(m, "", "").InterfaceType; got != "ollama" {
t.Errorf("expected explicit interface to win, got %q", got)
}
}
+9 -1
View File
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
secutils "github.com/Tencent/WeKnora/internal/utils"
openai "github.com/sashabaranov/go-openai"
)
@@ -53,7 +54,14 @@ func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) {
apiCfg.BaseURL = config.BaseURL
}
}
apiCfg.HTTPClient = &http.Client{Timeout: defaultTimeout}
httpClient := &http.Client{Timeout: defaultTimeout}
// 注入用户自定义 HTTP header(类似 OpenAI Python SDK 的 extra_headers)
if len(config.CustomHeaders) > 0 {
apiCfg.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, config.CustomHeaders)
} else {
apiCfg.HTTPClient = httpClient
}
return &RemoteAPIVLM{
modelName: config.ModelName,
+44
View File
@@ -30,10 +30,54 @@ type Config struct {
InterfaceType string // "ollama" or "openai" (default)
Provider string
Extra map[string]any
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
AppSecret string
}
// ConfigFromModel 根据 types.Model 构造 vlm.Config。
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。
// InterfaceType 会根据 source / 模型参数自动回退到合理默认值。
func ConfigFromModel(m *types.Model, appID, appSecret string) *Config {
if m == nil {
return nil
}
ifType := m.Parameters.InterfaceType
if ifType == "" {
if m.Source == types.ModelSourceLocal {
ifType = "ollama"
} else {
ifType = "openai"
}
}
return &Config{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
InterfaceType: ifType,
Provider: m.Parameters.Provider,
Extra: stringMapToAnyMap(m.Parameters.ExtraConfig),
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
}
}
func stringMapToAnyMap(in map[string]string) map[string]any {
if in == nil {
return nil
}
out := make(map[string]any, len(in))
for k, v := range in {
out[k] = v
}
return out
}
// NewVLM creates a VLM instance based on the provided configuration.
func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
v, err := newVLM(config, ollamaService)