Files
Enterprise-Knowledge-Base/internal/models/embedding/azure_openai.go
T
wizardchen fd3e2992b1 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.
2026-04-23 23:36:40 +08:00

204 lines
5.5 KiB
Go

package embedding
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// AzureOpenAIEmbedder implements text vectorization using Azure OpenAI API
type AzureOpenAIEmbedder struct {
apiKey string
baseURL string
modelName string
truncatePromptTokens int
dimensions int
modelID string
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"`
EncodingFormat string `json:"encoding_format,omitempty"`
Dimensions int `json:"dimensions,omitempty"`
}
// NewAzureOpenAIEmbedder creates a new Azure OpenAI embedder
func NewAzureOpenAIEmbedder(apiKey, baseURL, modelName string,
truncatePromptTokens int, dimensions int, modelID string,
apiVersion string, pooler EmbedderPooler,
) (*AzureOpenAIEmbedder, error) {
if baseURL == "" {
return nil, fmt.Errorf("Azure resource endpoint (base URL) is required")
}
if modelName == "" {
return nil, fmt.Errorf("deployment name (model name) is required")
}
if apiVersion == "" {
apiVersion = "2024-10-21"
}
if truncatePromptTokens == 0 {
truncatePromptTokens = 511
}
return &AzureOpenAIEmbedder{
apiKey: apiKey,
baseURL: baseURL,
modelName: modelName,
truncatePromptTokens: truncatePromptTokens,
dimensions: dimensions,
modelID: modelID,
apiVersion: apiVersion,
httpClient: &http.Client{Timeout: 60 * time.Second},
maxRetries: 3,
EmbedderPooler: pooler,
}, nil
}
func (e *AzureOpenAIEmbedder) 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 *AzureOpenAIEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
reqBody := azureOpenAIEmbedRequest{
Model: e.modelName,
Input: texts,
EncodingFormat: "float",
}
if e.supportsDimensionsParam() {
reqBody.Dimensions = e.dimensions
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
logger.GetLogger(ctx).Debugf("AzureOpenAIEmbedder BatchEmbed: model=%s, input_count=%d",
e.modelName, len(texts))
resp, err := e.doRequestWithRetry(ctx, jsonData)
if err != nil {
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 {
return nil, fmt.Errorf("read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
bodyStr := string(body)
if len(bodyStr) > 1000 {
bodyStr = bodyStr[:1000] + "... (truncated)"
}
return nil, fmt.Errorf("Azure Embedding API error: Http Status %s, Response: %s", resp.Status, bodyStr)
}
var response OpenAIEmbedResponse
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
embeddings := make([][]float32, 0, len(response.Data))
for _, data := range response.Data {
embeddings = append(embeddings, data.Embedding)
}
return embeddings, nil
}
func (e *AzureOpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) (*http.Response, error) {
url := fmt.Sprintf("%s/openai/deployments/%s/embeddings?api-version=%s",
e.baseURL, e.modelName, e.apiVersion)
var resp *http.Response
var err error
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
}
select {
case <-time.After(backoffTime):
case <-ctx.Done():
return nil, ctx.Err()
}
}
req, reqErr := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if reqErr != nil {
err = reqErr
continue
}
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 {
return resp, nil
}
}
return nil, err
}
func (e *AzureOpenAIEmbedder) supportsDimensionsParam() bool {
if e.dimensions <= 0 {
return false
}
// Azure only supports the dimensions parameter on newer embeddings APIs.
if strings.TrimSpace(e.apiVersion) < "2024-10-21" {
return false
}
modelRef := strings.ToLower(strings.TrimSpace(e.modelID))
if modelRef == "" {
modelRef = strings.ToLower(strings.TrimSpace(e.modelName))
}
// Fixed-dimension legacy models reject the field entirely.
if strings.Contains(modelRef, "ada-002") {
return false
}
return strings.Contains(modelRef, "text-embedding-3-small") ||
strings.Contains(modelRef, "text-embedding-3-large")
}
func (e *AzureOpenAIEmbedder) GetModelName() string { return e.modelName }
func (e *AzureOpenAIEmbedder) GetDimensions() int { return e.dimensions }
func (e *AzureOpenAIEmbedder) GetModelID() string { return e.modelID }