2025-08-05 07:08:07 +00:00
|
|
|
|
package chat
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2025-09-08 06:52:07 +00:00
|
|
|
|
"bytes"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"context"
|
2025-09-08 06:52:07 +00:00
|
|
|
|
"encoding/json"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"fmt"
|
2026-01-20 08:20:43 +00:00
|
|
|
|
"io"
|
2025-09-08 06:52:07 +00:00
|
|
|
|
"net/http"
|
2026-02-04 10:44:50 +00:00
|
|
|
|
"strings"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2025-11-05 15:18:44 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2025-12-28 17:31:27 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/models/provider"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
2026-03-11 09:17:32 +00:00
|
|
|
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
2025-08-05 07:08:07 +00:00
|
|
|
|
"github.com/sashabaranov/go-openai"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
// RemoteAPIChat 实现了基于 OpenAI 兼容 API 的聊天。
|
|
|
|
|
|
// 它本身只负责通用的请求/响应/流式处理;所有 provider 特定行为都委托给
|
|
|
|
|
|
// providerAdapter(见 provider.go),thinking 编码委托给 ThinkingStrategy
|
|
|
|
|
|
// (见 thinking.go)。
|
2025-08-05 07:08:07 +00:00
|
|
|
|
type RemoteAPIChat struct {
|
|
|
|
|
|
modelName string
|
|
|
|
|
|
client *openai.Client
|
|
|
|
|
|
modelID string
|
2025-09-08 06:52:07 +00:00
|
|
|
|
baseURL string
|
|
|
|
|
|
apiKey string
|
2026-01-20 08:20:43 +00:00
|
|
|
|
provider provider.ProviderName
|
2026-04-13 09:23:16 +00:00
|
|
|
|
appID string
|
|
|
|
|
|
appSecret string
|
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 15:13:10 +00:00
|
|
|
|
// customHeaders 为用户在模型配置中指定的自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
|
|
|
|
|
|
customHeaders map[string]string
|
2025-09-08 06:52:07 +00:00
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
// adapter 承载所有 provider 特定行为(thinking / 参数特判 / endpoint / 鉴权 / 消息变换)。
|
|
|
|
|
|
adapter providerAdapter
|
|
|
|
|
|
// thinkingOverride 来自 extra_config.thinking_control,非 nil 时覆盖 adapter.Thinking()。
|
|
|
|
|
|
thinkingOverride ThinkingStrategy
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-20 08:20:43 +00:00
|
|
|
|
// NewRemoteAPIChat 创建远程 API 聊天实例
|
2025-08-05 07:08:07 +00:00
|
|
|
|
func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
|
2026-03-26 03:07:19 +00:00
|
|
|
|
if chatConfig.BaseURL != "" {
|
|
|
|
|
|
if err := secutils.ValidateURLForSSRF(chatConfig.BaseURL); err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("baseURL SSRF check failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
apiKey := chatConfig.APIKey
|
2025-12-28 17:31:27 +00:00
|
|
|
|
providerName := provider.ProviderName(chatConfig.Provider)
|
|
|
|
|
|
if providerName == "" {
|
|
|
|
|
|
providerName = provider.DetectProvider(chatConfig.BaseURL)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-07 11:12:58 +00:00
|
|
|
|
var config openai.ClientConfig
|
|
|
|
|
|
if providerName == provider.ProviderAzureOpenAI {
|
|
|
|
|
|
config = openai.DefaultAzureConfig(apiKey, chatConfig.BaseURL)
|
2026-04-07 12:24:04 +00:00
|
|
|
|
config.AzureModelMapperFunc = func(model string) string {
|
|
|
|
|
|
return model
|
|
|
|
|
|
}
|
2026-04-13 09:23:16 +00:00
|
|
|
|
if chatConfig.ExtraConfig != nil {
|
|
|
|
|
|
if v, ok := chatConfig.ExtraConfig["api_version"]; ok {
|
|
|
|
|
|
config.APIVersion = v
|
2026-04-07 11:12:58 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
config = openai.DefaultConfig(apiKey)
|
|
|
|
|
|
if baseURL := chatConfig.BaseURL; baseURL != "" {
|
|
|
|
|
|
config.BaseURL = baseURL
|
2026-07-23 10:00:35 +00:00
|
|
|
|
} else if providerName == provider.ProviderDeepSeek {
|
|
|
|
|
|
config.BaseURL = provider.DeepSeekBaseURL
|
2026-04-07 11:12:58 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
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 15:13:10 +00:00
|
|
|
|
// 如果指定了 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)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-13 09:23:16 +00:00
|
|
|
|
modelName := chatConfig.ModelName
|
|
|
|
|
|
if chatConfig.ExtraConfig != nil {
|
|
|
|
|
|
if override := strings.TrimSpace(chatConfig.ExtraConfig["remote_model_name"]); override != "" {
|
|
|
|
|
|
modelName = override
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if providerName == provider.ProviderWeKnoraCloud {
|
|
|
|
|
|
if chatConfig.AppID == "" {
|
|
|
|
|
|
return nil, fmt.Errorf("WeKnoraCloud provider: AppID is required")
|
|
|
|
|
|
}
|
|
|
|
|
|
if chatConfig.AppSecret == "" {
|
|
|
|
|
|
return nil, fmt.Errorf("WeKnoraCloud provider: AppSecret is required")
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
return &RemoteAPIChat{
|
2026-06-05 06:42:08 +00:00
|
|
|
|
modelName: modelName,
|
|
|
|
|
|
client: openai.NewClientWithConfig(config),
|
|
|
|
|
|
modelID: chatConfig.ModelID,
|
2026-07-23 10:00:35 +00:00
|
|
|
|
baseURL: strings.TrimRight(config.BaseURL, "/"),
|
2026-06-05 06:42:08 +00:00
|
|
|
|
apiKey: apiKey,
|
|
|
|
|
|
provider: providerName,
|
|
|
|
|
|
appID: chatConfig.AppID,
|
|
|
|
|
|
appSecret: chatConfig.AppSecret,
|
|
|
|
|
|
customHeaders: chatConfig.CustomHeaders,
|
|
|
|
|
|
adapter: resolveProvider(providerName, modelName),
|
|
|
|
|
|
thinkingOverride: parseThinkingOverride(chatConfig.ExtraConfig),
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
// authCreds bundles the credentials passed to the adapter's Auth method.
|
|
|
|
|
|
func (c *RemoteAPIChat) authCreds() authCreds {
|
|
|
|
|
|
return authCreds{APIKey: c.apiKey, AppID: c.appID, AppSecret: c.appSecret}
|
2026-01-20 08:20:43 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
// shapedRequest builds the standard request and applies the adapter's message
|
|
|
|
|
|
// transform and parameter shaping (but not thinking, which may wrap the body).
|
|
|
|
|
|
func (c *RemoteAPIChat) shapedRequest(messages []Message, opts *ChatOptions, isStream bool) openai.ChatCompletionRequest {
|
|
|
|
|
|
req := c.BuildChatCompletionRequest(messages, opts, isStream)
|
|
|
|
|
|
req.Messages = c.adapter.TransformMessages(req.Messages)
|
|
|
|
|
|
c.adapter.ShapeRequest(&req, opts, isStream)
|
|
|
|
|
|
return req
|
2026-04-13 09:23:16 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
// buildOutbound assembles the final outbound request: the body to send, the
|
|
|
|
|
|
// endpoint override (empty for the standard endpoint), and whether the raw HTTP
|
|
|
|
|
|
// path is required. This is the single place that composes adapter + thinking,
|
|
|
|
|
|
// replacing the former buildRequestCustomizer plumbing.
|
|
|
|
|
|
func (c *RemoteAPIChat) buildOutbound(
|
|
|
|
|
|
messages []Message, opts *ChatOptions, isStream bool,
|
2026-06-09 09:30:42 +00:00
|
|
|
|
) (body any, endpoint string, useRawHTTP bool, err error) {
|
2026-06-05 06:42:08 +00:00
|
|
|
|
req := c.shapedRequest(messages, opts, isStream)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
thinking := c.thinkingOverride
|
|
|
|
|
|
if thinking == nil {
|
|
|
|
|
|
thinking = c.adapter.Thinking()
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
customBody, useRaw := thinking.Apply(&req, opts, isStream)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
body = &req
|
|
|
|
|
|
if customBody != nil {
|
|
|
|
|
|
body = customBody
|
2026-03-22 15:15:33 +00:00
|
|
|
|
}
|
2026-06-09 09:30:42 +00:00
|
|
|
|
body, err = c.shapeProviderRequest(body, req, messages)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, "", false, err
|
|
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
endpoint = c.adapter.Endpoint(c.baseURL, c.modelID, isStream)
|
|
|
|
|
|
useRawHTTP = useRaw || c.adapter.ForceRawHTTP() || endpoint != ""
|
2026-06-09 09:30:42 +00:00
|
|
|
|
return body, endpoint, useRawHTTP, nil
|
2026-01-20 08:20:43 +00:00
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2026-01-20 08:20:43 +00:00
|
|
|
|
// logRequest 记录请求日志
|
|
|
|
|
|
func (c *RemoteAPIChat) logRequest(ctx context.Context, req any, isStream bool) {
|
2025-12-24 02:34:41 +00:00
|
|
|
|
if jsonData, err := json.MarshalIndent(req, "", " "); err == nil {
|
2026-06-05 06:42:08 +00:00
|
|
|
|
logger.Infof(ctx, "[LLM Request] model=%s, stream=%v, request:\n%s",
|
|
|
|
|
|
c.modelName, isStream, secutils.CompactImageDataURLForLog(string(jsonData)))
|
2025-12-24 02:34:41 +00:00
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Chat 进行非流式聊天
|
|
|
|
|
|
func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
|
2026-05-09 16:06:53 +00:00
|
|
|
|
// 仅在调用方未设置 deadline 时附加一个兜底超时,防止 hung 请求永久阻塞 worker;
|
|
|
|
|
|
// 调用方若显式设置了更短或更长的 deadline,都会被原样尊重。
|
|
|
|
|
|
timeoutCtx, cancel := withLLMTimeout(ctx, defaultChatTimeout)
|
2026-05-09 08:23:07 +00:00
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
2026-06-09 09:30:42 +00:00
|
|
|
|
body, endpoint, useRawHTTP, err := c.buildOutbound(messages, opts, false)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
if useRawHTTP {
|
|
|
|
|
|
return c.chatWithRawHTTP(timeoutCtx, endpoint, body)
|
2026-03-11 02:48:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
req := *(body.(*openai.ChatCompletionRequest))
|
2026-05-09 08:23:07 +00:00
|
|
|
|
c.logRequest(timeoutCtx, req, false)
|
|
|
|
|
|
resp, err := c.client.CreateChatCompletion(timeoutCtx, req)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
if err != nil {
|
2026-03-11 09:17:32 +00:00
|
|
|
|
if isMultimodalNotSupportedError(err) {
|
2026-05-09 08:23:07 +00:00
|
|
|
|
logger.Warnf(timeoutCtx, "[LLM Request] Model %s does not support multimodal, retrying without images", c.modelName)
|
2026-03-11 09:17:32 +00:00
|
|
|
|
cleaned := stripImagesFromMessages(messages)
|
2026-06-05 06:42:08 +00:00
|
|
|
|
req = c.shapedRequest(cleaned, opts, false)
|
2026-05-09 08:23:07 +00:00
|
|
|
|
resp, err = c.client.CreateChatCompletion(timeoutCtx, req)
|
2026-03-11 09:17:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("create chat completion: %w", err)
|
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-26 08:45:51 +00:00
|
|
|
|
result, err := c.parseCompletionResponse(&resp)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
logUsage(timeoutCtx, c.modelName, &result.Usage)
|
2026-03-26 08:45:51 +00:00
|
|
|
|
return result, nil
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-20 08:20:43 +00:00
|
|
|
|
// chatWithRawHTTP 使用原始 HTTP 请求进行聊天(供自定义请求使用)
|
2026-03-11 02:48:26 +00:00
|
|
|
|
func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, customReq any) (*types.ChatResponse, error) {
|
2026-01-20 08:20:43 +00:00
|
|
|
|
jsonData, err := json.Marshal(customReq)
|
2025-09-08 06:52:07 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("marshal request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-11 02:48:26 +00:00
|
|
|
|
if endpoint == "" {
|
|
|
|
|
|
endpoint = c.baseURL + "/chat/completions"
|
|
|
|
|
|
}
|
2026-03-26 03:07:19 +00:00
|
|
|
|
if err := secutils.ValidateURLForSSRF(endpoint); err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("endpoint SSRF check failed: %w", err)
|
|
|
|
|
|
}
|
2026-04-14 09:13:16 +00:00
|
|
|
|
logger.Infof(ctx, "[LLM Request] Remote HTTP, endpoint=%s, model=%s, raw HTTP request:\n%s",
|
|
|
|
|
|
endpoint, c.modelName, secutils.CompactImageDataURLForLog(string(jsonData)))
|
|
|
|
|
|
|
2025-09-08 06:52:07 +00:00
|
|
|
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewBuffer(jsonData))
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("create request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
httpReq.Header.Set("Content-Type", "application/json")
|
2026-06-05 06:42:08 +00:00
|
|
|
|
c.adapter.Auth(httpReq, c.authCreds(), jsonData)
|
2025-09-08 06:52:07 +00:00
|
|
|
|
|
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 15:13:10 +00:00
|
|
|
|
// 注入用户自定义 header(保留头会在工具内部自动跳过)
|
|
|
|
|
|
secutils.ApplyCustomHeaders(httpReq, c.customHeaders)
|
|
|
|
|
|
|
2026-04-23 03:22:44 +00:00
|
|
|
|
logger.Infof(ctx, "[LLM Request] Remote HTTP, endpoint=%s, model=%s",
|
|
|
|
|
|
endpoint, c.modelName)
|
2026-04-14 09:13:16 +00:00
|
|
|
|
|
2026-03-24 08:26:23 +00:00
|
|
|
|
resp, err := rawHTTPClient.Do(httpReq)
|
2025-09-08 06:52:07 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("send request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
2026-01-20 08:20:43 +00:00
|
|
|
|
body, _ := io.ReadAll(resp.Body)
|
|
|
|
|
|
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
|
2025-09-08 06:52:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-09 09:30:42 +00:00
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("read response: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-08 06:52:07 +00:00
|
|
|
|
var chatResp openai.ChatCompletionResponse
|
2026-06-09 09:30:42 +00:00
|
|
|
|
if err := json.Unmarshal(body, &chatResp); err != nil {
|
2025-09-08 06:52:07 +00:00
|
|
|
|
return nil, fmt.Errorf("decode response: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-26 08:45:51 +00:00
|
|
|
|
result, err := c.parseCompletionResponse(&chatResp)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-06-09 09:30:42 +00:00
|
|
|
|
c.applyCompletionToolCallMetadata(body, result)
|
2026-07-23 10:00:35 +00:00
|
|
|
|
applyRawPromptCacheUsage(body, &result.Usage)
|
2026-06-05 06:42:08 +00:00
|
|
|
|
logUsage(ctx, c.modelName, &result.Usage)
|
2026-03-26 08:45:51 +00:00
|
|
|
|
return result, nil
|
2026-01-20 08:20:43 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
// ChatStream 进行流式聊天
|
2026-01-20 08:20:43 +00:00
|
|
|
|
func (c *RemoteAPIChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
|
2026-05-09 16:06:53 +00:00
|
|
|
|
// 仅在调用方未设置 deadline 时附加兜底超时;流式调用默认超时更长,
|
|
|
|
|
|
// 因为带思考/推理的模型可能数十秒甚至几分钟才产出首 token。
|
|
|
|
|
|
timeoutCtx, cancel := withLLMTimeout(ctx, defaultStreamTimeout)
|
2026-05-09 08:23:07 +00:00
|
|
|
|
|
2026-06-09 09:30:42 +00:00
|
|
|
|
body, endpoint, useRawHTTP, err := c.buildOutbound(messages, opts, true)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
cancel()
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
if useRawHTTP {
|
|
|
|
|
|
ch, err := c.chatStreamWithRawHTTP(timeoutCtx, endpoint, body)
|
2026-05-09 16:06:53 +00:00
|
|
|
|
return wrapStreamCancel(ch, err, cancel)
|
2026-03-11 02:48:26 +00:00
|
|
|
|
}
|
2026-06-05 06:42:08 +00:00
|
|
|
|
|
|
|
|
|
|
req := *(body.(*openai.ChatCompletionRequest))
|
2026-05-09 08:23:07 +00:00
|
|
|
|
c.logRequest(timeoutCtx, req, true)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2026-06-05 06:42:08 +00:00
|
|
|
|
streamDumper := newStreamPacketDumper(c.modelName, &req)
|
2026-06-03 18:35:54 +00:00
|
|
|
|
if streamDumper != nil {
|
|
|
|
|
|
logger.Infof(timeoutCtx, "[LLM Stream Raw Dump] writing packets to %s", streamDumper.Path())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
streamChan := make(chan types.StreamResponse)
|
|
|
|
|
|
|
2026-05-09 08:23:07 +00:00
|
|
|
|
stream, err := c.client.CreateChatCompletionStream(timeoutCtx, req)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
if err != nil {
|
2026-03-11 09:17:32 +00:00
|
|
|
|
if isMultimodalNotSupportedError(err) {
|
2026-05-09 08:23:07 +00:00
|
|
|
|
logger.Warnf(timeoutCtx, "[LLM Stream] Model %s does not support multimodal, retrying without images", c.modelName)
|
2026-03-11 09:17:32 +00:00
|
|
|
|
cleaned := stripImagesFromMessages(messages)
|
2026-06-05 06:42:08 +00:00
|
|
|
|
req = c.shapedRequest(cleaned, opts, true)
|
2026-05-09 08:23:07 +00:00
|
|
|
|
stream, err = c.client.CreateChatCompletionStream(timeoutCtx, req)
|
2026-03-11 09:17:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
if err != nil {
|
2026-05-09 08:23:07 +00:00
|
|
|
|
cancel()
|
2026-03-11 09:17:32 +00:00
|
|
|
|
close(streamChan)
|
|
|
|
|
|
return nil, fmt.Errorf("create chat completion stream: %w", err)
|
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-09 08:23:07 +00:00
|
|
|
|
go func() {
|
|
|
|
|
|
defer cancel()
|
2026-06-03 18:35:54 +00:00
|
|
|
|
if streamDumper != nil {
|
|
|
|
|
|
defer streamDumper.Close()
|
|
|
|
|
|
}
|
|
|
|
|
|
c.processStream(timeoutCtx, stream, streamChan, streamDumper)
|
2026-05-09 08:23:07 +00:00
|
|
|
|
}()
|
2026-01-20 08:20:43 +00:00
|
|
|
|
|
|
|
|
|
|
return streamChan, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-09 16:06:53 +00:00
|
|
|
|
// wrapStreamCancel 在子 channel 关闭后执行 cancel,避免 timeout context 泄漏。
|
|
|
|
|
|
// 当底层调用直接返回 error 时,立即调用 cancel 并将 error 透出。
|
|
|
|
|
|
func wrapStreamCancel(in <-chan types.StreamResponse, err error, cancel context.CancelFunc) (<-chan types.StreamResponse, error) {
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
cancel()
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
}
|
|
|
|
|
|
out := make(chan types.StreamResponse)
|
|
|
|
|
|
go func() {
|
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
defer close(out)
|
|
|
|
|
|
for v := range in {
|
|
|
|
|
|
out <- v
|
|
|
|
|
|
}
|
|
|
|
|
|
}()
|
|
|
|
|
|
return out, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-20 08:20:43 +00:00
|
|
|
|
// chatStreamWithRawHTTP 使用原始 HTTP 请求进行流式聊天
|
2026-03-11 02:48:26 +00:00
|
|
|
|
func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint string, customReq any) (<-chan types.StreamResponse, error) {
|
2026-01-20 08:20:43 +00:00
|
|
|
|
jsonData, err := json.Marshal(customReq)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("marshal request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-11 02:48:26 +00:00
|
|
|
|
if endpoint == "" {
|
|
|
|
|
|
endpoint = c.baseURL + "/chat/completions"
|
|
|
|
|
|
}
|
2026-03-26 03:07:19 +00:00
|
|
|
|
if err := secutils.ValidateURLForSSRF(endpoint); err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("endpoint SSRF check failed: %w", err)
|
|
|
|
|
|
}
|
2026-04-23 09:48:14 +00:00
|
|
|
|
|
|
|
|
|
|
if prettyJSON, pErr := json.MarshalIndent(customReq, "", " "); pErr == nil {
|
|
|
|
|
|
logger.Infof(ctx, "[LLM Stream Request] endpoint=%s, model=%s, stream=true, request:\n%s",
|
|
|
|
|
|
endpoint, c.modelName, secutils.CompactImageDataURLForLog(string(prettyJSON)))
|
|
|
|
|
|
} else {
|
|
|
|
|
|
logger.Infof(ctx, "[LLM Stream] endpoint=%s, model=%s", endpoint, c.modelName)
|
|
|
|
|
|
}
|
2026-01-20 08:20:43 +00:00
|
|
|
|
httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewBuffer(jsonData))
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("create request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
httpReq.Header.Set("Content-Type", "application/json")
|
2026-06-05 06:42:08 +00:00
|
|
|
|
c.adapter.Auth(httpReq, c.authCreds(), jsonData)
|
2026-01-20 08:20:43 +00:00
|
|
|
|
httpReq.Header.Set("Accept", "text/event-stream")
|
|
|
|
|
|
|
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 15:13:10 +00:00
|
|
|
|
// 注入用户自定义 header(保留头会在工具内部自动跳过)
|
|
|
|
|
|
secutils.ApplyCustomHeaders(httpReq, c.customHeaders)
|
|
|
|
|
|
|
2026-03-24 08:26:23 +00:00
|
|
|
|
resp, err := rawHTTPClient.Do(httpReq)
|
2026-01-20 08:20:43 +00:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return nil, fmt.Errorf("send request: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
|
|
body, _ := io.ReadAll(resp.Body)
|
|
|
|
|
|
resp.Body.Close()
|
|
|
|
|
|
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
streamChan := make(chan types.StreamResponse)
|
2026-06-03 18:35:54 +00:00
|
|
|
|
streamDumper := newStreamPacketDumper(c.modelName, customReq)
|
|
|
|
|
|
if streamDumper != nil {
|
|
|
|
|
|
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", streamDumper.Path())
|
|
|
|
|
|
}
|
2026-01-20 08:20:43 +00:00
|
|
|
|
|
2026-06-03 18:35:54 +00:00
|
|
|
|
go func() {
|
|
|
|
|
|
if streamDumper != nil {
|
|
|
|
|
|
defer streamDumper.Close()
|
|
|
|
|
|
}
|
|
|
|
|
|
c.processRawHTTPStream(ctx, resp, streamChan, streamDumper)
|
|
|
|
|
|
}()
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2026-01-20 08:20:43 +00:00
|
|
|
|
return streamChan, nil
|
|
|
|
|
|
}
|
2025-11-12 13:27:56 +00:00
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
// GetModelName 获取模型名称
|
|
|
|
|
|
func (c *RemoteAPIChat) GetModelName() string {
|
|
|
|
|
|
return c.modelName
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetModelID 获取模型ID
|
|
|
|
|
|
func (c *RemoteAPIChat) GetModelID() string {
|
|
|
|
|
|
return c.modelID
|
|
|
|
|
|
}
|
2026-01-20 08:20:43 +00:00
|
|
|
|
|
|
|
|
|
|
// GetProvider 获取 provider 名称
|
|
|
|
|
|
func (c *RemoteAPIChat) GetProvider() provider.ProviderName {
|
|
|
|
|
|
return c.provider
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetBaseURL 获取 baseURL
|
|
|
|
|
|
func (c *RemoteAPIChat) GetBaseURL() string {
|
|
|
|
|
|
return c.baseURL
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetAPIKey 获取 apiKey
|
|
|
|
|
|
func (c *RemoteAPIChat) GetAPIKey() string {
|
|
|
|
|
|
return c.apiKey
|
|
|
|
|
|
}
|