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:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user