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:
@@ -250,13 +250,22 @@ export function getCurrentConfigByKB(kbId: string): Promise<InitializationConfig
|
||||
});
|
||||
}
|
||||
|
||||
// 所有"测试连接"接口共用的通用可选参数。
|
||||
// customHeaders / extraConfig / interfaceType 对应后端 ModelTestRequest 里的同名字段,
|
||||
// 会被透传给真正的模型装配流程,保证测试连接与生产调用走完全相同的路径。
|
||||
interface BaseModelTestPayload {
|
||||
customHeaders?: Record<string, string>;
|
||||
extraConfig?: Record<string, string>;
|
||||
interfaceType?: string;
|
||||
}
|
||||
|
||||
// 检查远程API模型
|
||||
export function checkRemoteModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
provider?: string;
|
||||
}): Promise<{
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
@@ -280,7 +289,7 @@ export function testEmbeddingModel(modelConfig: {
|
||||
apiKey?: string;
|
||||
dimension?: number;
|
||||
provider?: string;
|
||||
}): Promise<{ available: boolean; message?: string; dimension?: number }> {
|
||||
} & BaseModelTestPayload): Promise<{ available: boolean; message?: string; dimension?: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
post('/api/v1/initialization/embedding/test', modelConfig)
|
||||
.then((response: any) => {
|
||||
@@ -298,7 +307,8 @@ export function checkRerankModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
}): Promise<{
|
||||
provider?: string;
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
@@ -319,7 +329,8 @@ export function checkASRModel(modelConfig: {
|
||||
modelName: string;
|
||||
baseUrl: string;
|
||||
apiKey?: string;
|
||||
}): Promise<{
|
||||
provider?: string;
|
||||
} & BaseModelTestPayload): Promise<{
|
||||
available: boolean;
|
||||
message?: string;
|
||||
}> {
|
||||
|
||||
@@ -22,6 +22,9 @@ export interface ModelConfig {
|
||||
interface_type?: 'ollama' | 'openai'; // VLLM专用
|
||||
parameter_size?: string; // Ollama模型参数大小 (e.g., "7B", "13B", "70B")
|
||||
extra_config?: Record<string, string>; // Provider-specific configuration
|
||||
// 自定义 HTTP 请求头(类似 Python OpenAI SDK 的 extra_headers),
|
||||
// 会在调用远程模型 API 时附加到每个请求上。Authorization、Content-Type 等保留头会被忽略。
|
||||
custom_headers?: Record<string, string>;
|
||||
supports_vision?: boolean; // Whether the model accepts image/multimodal input
|
||||
};
|
||||
is_default?: boolean;
|
||||
|
||||
@@ -218,6 +218,46 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 自定义 HTTP Header(类似 OpenAI Python SDK 的 extra_headers) -->
|
||||
<div v-if="formData.provider !== 'weknoracloud'" class="form-item">
|
||||
<div class="custom-headers-header">
|
||||
<label class="form-label" style="margin-bottom: 0;">{{ $t('model.editor.customHeadersLabel') }}</label>
|
||||
<t-button variant="text" size="small" theme="primary" @click="addCustomHeader">
|
||||
<template #icon><t-icon name="add" /></template>
|
||||
{{ $t('model.editor.customHeadersAdd') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<p class="form-desc custom-headers-desc">{{ $t('model.editor.customHeadersDesc') }}</p>
|
||||
<div v-if="formData.customHeaders && formData.customHeaders.length > 0" class="custom-headers-list">
|
||||
<div
|
||||
v-for="(item, idx) in formData.customHeaders"
|
||||
:key="idx"
|
||||
class="custom-header-row"
|
||||
>
|
||||
<t-input
|
||||
v-model="item.key"
|
||||
:placeholder="$t('model.editor.customHeadersKeyPlaceholder')"
|
||||
class="custom-header-key"
|
||||
/>
|
||||
<t-input
|
||||
v-model="item.value"
|
||||
:placeholder="$t('model.editor.customHeadersValuePlaceholder')"
|
||||
class="custom-header-value"
|
||||
/>
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
theme="danger"
|
||||
@click="removeCustomHeader(idx)"
|
||||
:aria-label="$t('common.delete')"
|
||||
>
|
||||
<t-icon name="close" />
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Remote API 校验 -->
|
||||
<div class="form-item">
|
||||
<label class="form-label">{{ $t('model.editor.connectionTest') }}</label>
|
||||
@@ -314,6 +354,11 @@ import { getWeKnoraCloudStatus } from '@/api/model'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
|
||||
interface CustomHeaderItem {
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface ModelFormData {
|
||||
id: string
|
||||
name: string
|
||||
@@ -326,6 +371,8 @@ interface ModelFormData {
|
||||
interfaceType?: 'ollama' | 'openai'
|
||||
isDefault: boolean
|
||||
supportsVision?: boolean
|
||||
// 自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)
|
||||
customHeaders?: CustomHeaderItem[]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
@@ -571,7 +618,8 @@ const formData = ref<ModelFormData>({
|
||||
dimension: undefined,
|
||||
interfaceType: 'ollama',
|
||||
isDefault: false,
|
||||
supportsVision: false
|
||||
supportsVision: false,
|
||||
customHeaders: []
|
||||
})
|
||||
|
||||
const rules = computed(() => ({
|
||||
@@ -693,7 +741,12 @@ watch(() => props.visible, (val) => {
|
||||
loadProviders()
|
||||
|
||||
if (props.modelData) {
|
||||
formData.value = { ...props.modelData }
|
||||
formData.value = {
|
||||
...props.modelData,
|
||||
customHeaders: Array.isArray(props.modelData.customHeaders)
|
||||
? props.modelData.customHeaders.map(h => ({ key: h.key, value: h.value }))
|
||||
: []
|
||||
}
|
||||
} else {
|
||||
resetForm()
|
||||
}
|
||||
@@ -726,7 +779,8 @@ const resetForm = () => {
|
||||
dimension: undefined, // 默认不填,让用户手动输入或通过检测按钮获取
|
||||
interfaceType: undefined,
|
||||
isDefault: false,
|
||||
supportsVision: false
|
||||
supportsVision: false,
|
||||
customHeaders: []
|
||||
}
|
||||
modelChecked.value = false
|
||||
modelAvailable.value = false
|
||||
@@ -765,6 +819,19 @@ const generateId = () => {
|
||||
return `model_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
|
||||
}
|
||||
|
||||
// 自定义 HTTP Header 编辑
|
||||
const addCustomHeader = () => {
|
||||
if (!Array.isArray(formData.value.customHeaders)) {
|
||||
formData.value.customHeaders = []
|
||||
}
|
||||
formData.value.customHeaders.push({ key: '', value: '' })
|
||||
}
|
||||
|
||||
const removeCustomHeader = (idx: number) => {
|
||||
if (!Array.isArray(formData.value.customHeaders)) return
|
||||
formData.value.customHeaders.splice(idx, 1)
|
||||
}
|
||||
|
||||
// 过滤后的模型列表
|
||||
const filteredOllamaModels = computed(() => {
|
||||
if (!searchKeyword.value) return ollamaModelList.value
|
||||
@@ -900,7 +967,23 @@ const checkRemoteAPI = async () => {
|
||||
|
||||
try {
|
||||
let result: any
|
||||
|
||||
|
||||
// 把表单里 Key-Value 数组形式的自定义 Header 转成后端期望的 map。
|
||||
// 跟 ModelSettings.vue 保存时一致,空行自动丢弃,保证测试连接与真正保存后的
|
||||
// 生产调用使用完全相同的 Header 集合。
|
||||
const customHeaders: Record<string, string> = {}
|
||||
if (Array.isArray(formData.value.customHeaders)) {
|
||||
for (const item of formData.value.customHeaders) {
|
||||
const key = (item?.key ?? '').trim()
|
||||
const value = (item?.value ?? '').trim()
|
||||
if (key && value) customHeaders[key] = value
|
||||
}
|
||||
}
|
||||
// 只在非空时带上字段,避免在 URL query / 日志里出现空对象
|
||||
const headerPayload = Object.keys(customHeaders).length > 0
|
||||
? { customHeaders }
|
||||
: {}
|
||||
|
||||
// 根据模型类型调用不同的校验接口
|
||||
switch (props.modelType) {
|
||||
case 'chat':
|
||||
@@ -909,7 +992,8 @@ const checkRemoteAPI = async () => {
|
||||
modelName: formData.value.modelName,
|
||||
baseUrl: formData.value.baseUrl,
|
||||
apiKey: formData.value.apiKey || '',
|
||||
provider: formData.value.provider
|
||||
provider: formData.value.provider,
|
||||
...headerPayload,
|
||||
})
|
||||
break
|
||||
|
||||
@@ -921,7 +1005,8 @@ const checkRemoteAPI = async () => {
|
||||
baseUrl: formData.value.baseUrl,
|
||||
apiKey: formData.value.apiKey || '',
|
||||
dimension: formData.value.dimension,
|
||||
provider: formData.value.provider
|
||||
provider: formData.value.provider,
|
||||
...headerPayload,
|
||||
})
|
||||
// 如果测试成功且返回了维度,自动填充
|
||||
if (result.available && result.dimension) {
|
||||
@@ -935,7 +1020,9 @@ const checkRemoteAPI = async () => {
|
||||
result = await checkRerankModel({
|
||||
modelName: formData.value.modelName,
|
||||
baseUrl: formData.value.baseUrl,
|
||||
apiKey: formData.value.apiKey || ''
|
||||
apiKey: formData.value.apiKey || '',
|
||||
provider: formData.value.provider,
|
||||
...headerPayload,
|
||||
})
|
||||
break
|
||||
|
||||
@@ -946,7 +1033,8 @@ const checkRemoteAPI = async () => {
|
||||
modelName: formData.value.modelName,
|
||||
baseUrl: formData.value.baseUrl,
|
||||
apiKey: formData.value.apiKey || '',
|
||||
provider: formData.value.provider
|
||||
provider: formData.value.provider,
|
||||
...headerPayload,
|
||||
})
|
||||
break
|
||||
|
||||
@@ -955,7 +1043,9 @@ const checkRemoteAPI = async () => {
|
||||
result = await checkASRModel({
|
||||
modelName: formData.value.modelName,
|
||||
baseUrl: formData.value.baseUrl,
|
||||
apiKey: formData.value.apiKey || ''
|
||||
apiKey: formData.value.apiKey || '',
|
||||
provider: formData.value.provider,
|
||||
...headerPayload,
|
||||
})
|
||||
break
|
||||
|
||||
@@ -1682,6 +1772,55 @@ const handleOverlayMouseUp = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义 HTTP Header 区域
|
||||
.custom-headers-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.custom-headers-desc {
|
||||
margin: 0 0 10px 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.custom-headers-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.custom-header-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.custom-header-key {
|
||||
flex: 0 0 38%;
|
||||
}
|
||||
|
||||
.custom-header-value {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
:deep(.t-button) {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.form-desc {
|
||||
margin: 4px 0 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
// Ollama不可用提示样式
|
||||
.ollama-unavailable-tip {
|
||||
display: flex;
|
||||
|
||||
@@ -2349,6 +2349,11 @@ export default {
|
||||
baseUrlPlaceholderAsr: 'e.g. https://api.openai.com/v1',
|
||||
apiKeyOptional: 'API Key (optional)',
|
||||
apiKeyPlaceholder: 'Enter API Key',
|
||||
customHeadersLabel: 'Custom Request Headers (optional)',
|
||||
customHeadersDesc: 'Extra HTTP headers appended to requests to the remote model API (e.g. for enterprise gateway auth or tracing). Reserved headers like Authorization / Content-Type are ignored.',
|
||||
customHeadersAdd: 'Add Header',
|
||||
customHeadersKeyPlaceholder: 'Header name',
|
||||
customHeadersValuePlaceholder: 'Header value',
|
||||
connectionTest: 'Connection Test',
|
||||
testing: 'Testing...',
|
||||
testConnection: 'Test Connection',
|
||||
|
||||
@@ -1686,6 +1686,11 @@ export default {
|
||||
baseUrlPlaceholderAsr: "예: https://api.openai.com/v1",
|
||||
apiKeyOptional: "API 키 (선택)",
|
||||
apiKeyPlaceholder: "API 키 입력",
|
||||
customHeadersLabel: "사용자 정의 요청 헤더 (선택)",
|
||||
customHeadersDesc: "원격 모델 API 호출 시 추가되는 HTTP 헤더입니다. 기업 게이트웨이 인증이나 추적 등에 사용할 수 있으며, Authorization / Content-Type 같은 예약 헤더는 무시됩니다.",
|
||||
customHeadersAdd: "헤더 추가",
|
||||
customHeadersKeyPlaceholder: "헤더 이름",
|
||||
customHeadersValuePlaceholder: "헤더 값",
|
||||
connectionTest: "연결 테스트",
|
||||
testing: "테스트 중...",
|
||||
testConnection: "연결 테스트",
|
||||
|
||||
@@ -1527,6 +1527,11 @@ export default {
|
||||
baseUrlPlaceholderAsr: 'например: https://api.openai.com/v1',
|
||||
apiKeyOptional: 'API Key (опционально)',
|
||||
apiKeyPlaceholder: 'Введите API Key',
|
||||
customHeadersLabel: 'Пользовательские заголовки запроса (опционально)',
|
||||
customHeadersDesc: 'Дополнительные HTTP-заголовки, добавляемые к запросам к удалённому API модели (например, для авторизации корпоративного шлюза или трассировки). Зарезервированные заголовки, такие как Authorization / Content-Type, игнорируются.',
|
||||
customHeadersAdd: 'Добавить заголовок',
|
||||
customHeadersKeyPlaceholder: 'Имя заголовка',
|
||||
customHeadersValuePlaceholder: 'Значение заголовка',
|
||||
connectionTest: 'Проверка соединения',
|
||||
testing: 'Проверка...',
|
||||
testConnection: 'Проверить соединение',
|
||||
|
||||
@@ -1698,6 +1698,11 @@ export default {
|
||||
baseUrlPlaceholderAsr: "例如:https://api.openai.com/v1",
|
||||
apiKeyOptional: "API Key(可选)",
|
||||
apiKeyPlaceholder: "输入 API Key",
|
||||
customHeadersLabel: "自定义请求头(可选)",
|
||||
customHeadersDesc: "调用远程模型 API 时附加的 HTTP 请求头,常用于企业网关鉴权、链路追踪等场景;Authorization、Content-Type 等保留头会被自动忽略。",
|
||||
customHeadersAdd: "添加请求头",
|
||||
customHeadersKeyPlaceholder: "Header 名称",
|
||||
customHeadersValuePlaceholder: "Header 值",
|
||||
connectionTest: "连接测试",
|
||||
testing: "测试中...",
|
||||
testConnection: "测试连接",
|
||||
|
||||
@@ -350,7 +350,11 @@ function convertToLegacyFormat(model: ModelConfig) {
|
||||
provider: model.parameters.provider || '', // 添加 provider 字段
|
||||
dimension: model.parameters.embedding_parameters?.dimension,
|
||||
isBuiltin: model.is_builtin || false,
|
||||
supportsVision: model.parameters.supports_vision || false
|
||||
supportsVision: model.parameters.supports_vision || false,
|
||||
// 将后端 map 形式转换为前端可编辑的数组形式
|
||||
customHeaders: model.parameters.custom_headers
|
||||
? Object.entries(model.parameters.custom_headers).map(([key, value]) => ({ key, value: String(value) }))
|
||||
: []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,6 +430,18 @@ const handleModelSave = async (modelData: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 将前端 Key-Value 数组形式的自定义 Header 转换成后端期望的 map
|
||||
const customHeadersMap: Record<string, string> = {}
|
||||
if (Array.isArray(modelData.customHeaders)) {
|
||||
for (const item of modelData.customHeaders) {
|
||||
const key = (item?.key ?? '').trim()
|
||||
const value = (item?.value ?? '').trim()
|
||||
if (key && value) {
|
||||
customHeadersMap[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 将前端格式转换为后端格式
|
||||
const apiModelData: ModelConfig = {
|
||||
name: modelData.modelName.trim(), // 使用 modelName 作为 name,并去除首尾空格
|
||||
@@ -436,6 +452,7 @@ const handleModelSave = async (modelData: any) => {
|
||||
base_url: modelData.baseUrl?.trim() || '',
|
||||
api_key: modelData.apiKey?.trim() || '',
|
||||
provider: modelData.provider || '', // 添加 provider 字段
|
||||
...(Object.keys(customHeadersMap).length > 0 ? { custom_headers: customHeadersMap } : {}),
|
||||
...(currentModelType.value === 'embedding' && modelData.dimension ? {
|
||||
embedding_parameters: {
|
||||
dimension: modelData.dimension,
|
||||
|
||||
Reference in New Issue
Block a user