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