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
+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 {