Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat: add workspace default settings for models and web search (#4822)

lyingbugdacb9c2643bd
diff --git a/frontend/src/api/default-settings.ts b/frontend/src/api/default-settings.ts
new file mode 100644
index 000000000..3fa37d48e
--- /dev/null
+++ b/frontend/src/api/default-settings.ts
@@ -0,0 +1,20 @@
+import { get, put } from '@/utils/request'
+
+// DefaultSettings is the workspace's default model choice per slot. An empty
+// ID leaves the slot to the deployment default.
+export interface DefaultSettings {
+ chat_model_id: string
+ utility_model_id: string
+ embedding_model_id: string
+ rerank_model_id: string
+ vlm_model_id: string
+ asr_model_id: string
+}
+
+export function getTenantDefaultSettings() {
+ return get<{ success: boolean; data: DefaultSettings }>('/api/v1/tenants/kv/default-settings')
+}
+
+export function updateTenantDefaultSettings(settings: DefaultSettings) {
+ return put<{ success: boolean; data: DefaultSettings }>('/api/v1/tenants/kv/default-settings', settings)
+}
diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts
index 69f6b1c43..124773069 100644
--- a/frontend/src/api/model/index.ts
+++ b/frontend/src/api/model/index.ts
@@ -89,6 +89,7 @@ export interface ModelConfig {
// context window. Computed by the backend from provider + name + overrides.
capabilities?: ModelCapabilities;
is_default?: boolean;
+ default_for?: string[];
is_builtin?: boolean;
status?: string;
// Per-field configured? metadata from the main response. For builtin
diff --git a/frontend/src/api/web-search-provider.ts b/frontend/src/api/web-search-provider.ts
index 425c40134..fc73ff870 100644
--- a/frontend/src/api/web-search-provider.ts
+++ b/frontend/src/api/web-search-provider.ts
@@ -1,4 +1,4 @@
-import { get, post, put, del } from '@/utils/request'
+import { get, post, put, patch, del } from '@/utils/request'
// WebSearchProviderEntity represents a configured web search provider instance
export interface WebSearchProviderEntity {
@@ -71,6 +71,14 @@ export function updateWebSearchProvider(id: string, data: Partial<WebSearchProvi
return put(`/api/v1/web-search-providers/${id}`, data)
}
+// Change display/default settings only; connection parameters are preserved
+export function patchWebSearchProvider(
+ id: string,
+ data: { name?: string; description?: string; is_default?: boolean },
+) {
+ return patch(`/api/v1/web-search-providers/${id}`, data)
+}
+
// Delete a web search provider
export function deleteWebSearchProvider(id: string) {
return del(`/api/v1/web-search-providers/${id}`)
diff --git a/frontend/src/components/ModelSelector.vue b/frontend/src/components/ModelSelector.vue
index 77525d1b9..c779fac12 100644
--- a/frontend/src/components/ModelSelector.vue
+++ b/frontend/src/components/ModelSelector.vue
@@ -33,7 +33,7 @@
<span class="model-name">{{ modelDisplayName(model) }}</span>
<span v-if="model.display_name" class="model-raw-name">{{ model.name }}</span>
<t-tag v-if="model.is_builtin" size="small" theme="primary">{{ $t('model.builtinTag') }}</t-tag>
- <t-tag v-if="model.is_default" size="small" theme="success">{{ $t('model.defaultTag') }}</t-tag>
+ <t-tag v-if="isDefaultModelForType(model, modelType)" size="small" theme="success">{{ $t('model.defaultTag') }}</t-tag>
<span
v-if="showContextWindow"
class="model-ctx"
@@ -65,6 +65,7 @@ import { useChatResourcesStore } from '@/stores/chatResources'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { filterModelsByType } from './modelSelectorFilter'
+import { isDefaultModelForType } from '@/utils/modelDefaults'
import {
formatContextWindow,
isDefaultContextWindow,
diff --git a/frontend/src/components/modelSelectorFilter.ts b/frontend/src/components/modelSelectorFilter.ts
index c7f642743..1ea658f85 100644
--- a/frontend/src/components/modelSelectorFilter.ts
+++ b/frontend/src/components/modelSelectorFilter.ts
@@ -1,4 +1,5 @@
import type { ModelConfig } from '@/api/model'
+import { modelSupportsType } from '../utils/modelDefaults'
export type ModelSelectorType = ModelConfig['type']
@@ -6,13 +7,5 @@ export function filterModelsByType(
allModels: ModelConfig[],
modelType: ModelSelectorType,
): ModelConfig[] {
- if (modelType === 'VLLM') {
- return allModels.filter(
- (m) =>
- m.type === 'VLLM' ||
- (m.type === 'KnowledgeQA' && m.parameters?.supports_vision === true),
- )
- }
-
- return allModels.filter((m) => m.type === modelType)
+ return allModels.filter((m) => modelSupportsType(m, modelType))
}
diff --git a/frontend/src/composables/useModalShell.test.ts b/frontend/src/composables/useModalShell.test.ts
index 53ba8fbab..2661e904b 100644
--- a/frontend/src/composables/useModalShell.test.ts
+++ b/frontend/src/composables/useModalShell.test.ts
@@ -92,7 +92,7 @@ function fixture() {
app.mount({})
return { vm: instance.value, unmount: () => { app.unmount(); assert.deepEqual(errors, []) } }
}
- return { mount, dialogs, resources, ui, warnings, emit: modules['@/utils/assistantDataChange'].emitAssistantDataChange }
+ return { mount, dialogs, resources, chat, ui, warnings, emit: modules['@/utils/assistantDataChange'].emitAssistantDataChange }
}
async function settle() {
@@ -101,6 +101,29 @@ async function settle() {
await vue.nextTick()
}
+test('agent creation prefills vision and ASR defaults without enabling uploads or replacing explicit choices', async () => {
+ const f = fixture()
+ f.chat.allModels.push(
+ { id: 'vision', type: 'VLLM', is_default: true, capabilities: { thinking_levels: [] } },
+ { id: 'asr', type: 'ASR', is_default: true, capabilities: { thinking_levels: [] } },
+ )
+ const props = vue.reactive({ visible: false, mode: 'create' })
+ const { vm, unmount } = f.mount('../views/agent/AgentEditorModal.vue', props)
+ try {
+ props.visible = true
+ await settle()
+ assert.equal(vm.formData.config.vlm_model_id, 'vision')
+ assert.equal(vm.formData.config.asr_model_id, 'asr')
+ assert.ok(!vm.formData.config.image_upload_enabled)
+ assert.ok(!vm.formData.config.audio_upload_enabled)
+ vm.formData.config.vlm_model_id = 'explicit-vision'
+ vm.formData.config.asr_model_id = 'explicit-asr'
+ vm.applyDefaultModelsIfEmpty()
+ assert.equal(vm.formData.config.vlm_model_id, 'explicit-vision')
+ assert.equal(vm.formData.config.asr_model_id, 'explicit-asr')
+ } finally { unmount() }
+})
+
for (const mode of ['edit', 'create'] as const) {
test(`${mode}: initialization stays clean, while real edits require confirmation`, async () => {
const f = fixture()
diff --git a/frontend/src/config/settingsAccess.ts b/frontend/src/config/settingsAccess.ts
index 744630c98..9d63875e1 100644
--- a/frontend/src/config/settingsAccess.ts
+++ b/frontend/src/config/settingsAccess.ts
@@ -29,6 +29,8 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
members: 'viewer',
mymemory: 'viewer',
memory: 'admin',
+ // Members read which model each feature falls back to; editing is Admin+ inside.
+ defaults: 'viewer',
// Everyone sets their own preferences; the workspace part is Admin+ inside.
assistant: 'viewer',
// Every member fills in their own environment variables; the workspace-wide
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 04d488dd4..534f73e16 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2763,6 +2763,68 @@ export default {
clearSuccess: 'Your value was removed.',
updatedAt: 'You set this on {time}'
},
+ defaultSettings: {
+ loadFailed: 'Could not load defaults. Retry before editing.',
+ title: 'Defaults',
+ description: 'Manage the models and search engine this workspace uses by default, in one place.',
+ introTitle: 'Used whenever a resource does not pick its own',
+ introDescription: 'A model chosen on an agent, knowledge base or conversation always wins. Otherwise the workspace default here applies, and if none is set, the deployment\'s built-in default is used.',
+ readOnly: 'Only workspace admins can change these. You can see which defaults are in effect.',
+ modelGroup: 'Models',
+ webSearchGroup: 'Web search',
+ unsetPlaceholder: 'Not set (system default)',
+ followChatPlaceholder: 'Not set (follow default chat model)',
+ slots: {
+ chat: {
+ label: 'Default chat model',
+ description: 'Used by new agents and Q&A, and as the fallback for background tasks.',
+ none: 'No chat model is available, so Q&A and background generation will not work.',
+ },
+ utility: {
+ label: 'Lightweight generation model',
+ description: 'Used for short tasks such as session titles, MCP usage instructions and memory extraction. A faster, cheaper model works well.',
+ none: 'No chat model is available, so titles and instructions cannot be generated.',
+ },
+ embedding: {
+ label: 'Default embedding model',
+ description: 'Preselected for new knowledge bases. Existing knowledge bases are unchanged.',
+ none: 'No embedding model is available, so knowledge bases cannot be created.',
+ },
+ rerank: {
+ label: 'Default rerank model',
+ description: 'Used by searches and built-in agents that have no rerank model of their own.',
+ none: 'No rerank model is available, so search results keep their retrieval order.',
+ },
+ vlm: {
+ label: 'Default vision model',
+ description: 'Default choice for image understanding and multimodal parsing.',
+ none: 'No vision model is available, so image understanding is unavailable.',
+ },
+ asr: {
+ label: 'Default speech recognition model',
+ description: 'Default choice for audio and video transcription.',
+ none: 'No speech recognition model is available, so transcription is unavailable.',
+ },
+ },
+ hints: {
+ workspace: 'Using the workspace setting.',
+ system: 'Not set. Currently using the system default: {name}',
+ auto: 'Not set. Currently using the first available model: {name}',
+ followChat: 'Not set. Following the default chat model: {name}',
+ staleFallback: 'The selected model was deleted or is unavailable. Currently falling back to: {name}',
+ staleNone: 'The selected model was deleted or is unavailable, and there is nothing to fall back to.',
+ },
+ webSearch: {
+ label: 'Default search engine',
+ description: 'Used when web search is on for an agent that has no search engine of its own.',
+ unset: 'No default search engine. Agents without their own search engine cannot search the web.',
+ placeholder: 'Select a search engine',
+ },
+ toasts: {
+ saveSuccess: 'Defaults saved',
+ saveFailed: 'Save failed: {message}',
+ },
+ },
memoryWorkspaceSettings: {
title: 'Long-term memory',
description: 'Let the assistant remember what members tell it — who they are, how they like to work, stable facts and what they are working on — across conversations.',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index fccad85d5..1a7da47f8 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2763,6 +2763,68 @@ export default {
clearSuccess: '自分の値を削除しました。',
updatedAt: '{time}に設定しました'
},
+ defaultSettings: {
+ loadFailed: 'デフォルト設定を読み込めませんでした。再試行してから編集してください。',
+ title: 'デフォルト設定',
+ description: 'このワークスペースの各機能が既定で使うモデルと検索エンジンをまとめて管理します。',
+ introTitle: 'リソース側で指定がない場合に使われます',
+ introDescription: 'エージェント、ナレッジベース、会話で明示的に選んだモデルが優先されます。未選択の場合はここのワークスペース既定値、それも未設定ならデプロイ組み込みの既定モデルが使われます。',
+ readOnly: '変更できるのはワークスペース管理者のみです。現在有効な既定値は確認できます。',
+ modelGroup: 'モデル',
+ webSearchGroup: 'ウェブ検索',
+ unsetPlaceholder: '未設定(システム既定)',
+ followChatPlaceholder: '未設定(既定のチャットモデルに従う)',
+ slots: {
+ chat: {
+ label: '既定のチャットモデル',
+ description: '新規エージェントと Q&A で使われ、バックグラウンド処理の代替モデルにもなります。',
+ none: '利用可能なチャットモデルがないため、Q&A とバックグラウンド生成は使えません。',
+ },
+ utility: {
+ label: '軽量生成モデル',
+ description: 'セッションタイトル、MCP 利用説明、記憶抽出などの短いテキスト生成に使います。高速で安価なモデルがおすすめです。',
+ none: '利用可能なチャットモデルがないため、タイトルや説明を生成できません。',
+ },
+ embedding: {
+ label: '既定の Embedding モデル',
+ description: '新規ナレッジベース作成時に既定で選ばれます。既存のナレッジベースには影響しません。',
+ none: '利用可能な Embedding モデルがないため、ナレッジベースを作成できません。',
+ },
+ rerank: {
+ label: '既定の Rerank モデル',
+ description: '独自のリランクモデルを持たない検索と組み込みエージェントで使われます。',
+ none: '利用可能な Rerank モデルがないため、検索結果は取得順のまま返されます。',
+ },
+ vlm: {
+ label: '既定のビジョンモデル',
+ description: '画像理解とマルチモーダル解析の既定の選択です。',
+ none: '利用可能なビジョンモデルがないため、画像理解は使えません。',
+ },
+ asr: {
+ label: '既定の音声認識モデル',
+ description: '音声・動画の文字起こしの既定の選択です。',
+ none: '利用可能な音声認識モデルがないため、文字起こしは使えません。',
+ },
+ },
+ hints: {
+ workspace: 'ワークスペースの設定を使用中です。',
+ system: '未設定。現在はシステム既定を使用中:{name}',
+ auto: '未設定。現在は最初に利用可能なモデルを使用中:{name}',
+ followChat: '未設定。既定のチャットモデルに従います:{name}',
+ staleFallback: '選択したモデルは削除されたか利用できません。現在の代替:{name}',
+ staleNone: '選択したモデルは削除されたか利用できず、代替できるモデルもありません。',
+ },
+ webSearch: {
+ label: '既定の検索エンジン',
+ description: '独自の検索エンジンを持たないエージェントでウェブ検索が有効なときに使われます。',
+ unset: '既定の検索エンジンが未設定です。独自の検索エンジンを持たないエージェントはウェブ検索できません。',
+ placeholder: '検索エンジンを選択',
+ },
+ toasts: {
+ saveSuccess: 'デフォルト設定を保存しました',
+ saveFailed: '保存に失敗しました:{message}',
+ },
+ },
memoryWorkspaceSettings: {
title: '長期メモリ',
description: 'メンバーが会話で伝えた内容(本人の情報、仕事の進め方の好み、変わりにくい事実、取り組んでいること)を、会話をまたいでアシスタントが記憶できるようにします。',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index b26e90378..2dfaf6f7c 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6953,6 +6953,68 @@ export default {
clearSuccess: '내 값을 삭제했습니다.',
updatedAt: '{time}에 설정함'
},
+ defaultSettings: {
+ loadFailed: '기본 설정을 불러오지 못했습니다. 편집하기 전에 다시 시도하세요.',
+ title: '기본 설정',
+ description: '이 워크스페이스의 각 기능이 기본으로 사용하는 모델과 검색 엔진을 한곳에서 관리합니다.',
+ introTitle: '리소스에서 따로 지정하지 않으면 여기의 기본값을 사용합니다',
+ introDescription: '에이전트, 지식베이스, 대화에서 직접 선택한 모델이 우선합니다. 선택하지 않았으면 여기의 워크스페이스 기본값을, 그것도 없으면 배포에 내장된 기본 모델을 사용합니다.',
+ readOnly: '워크스페이스 관리자만 변경할 수 있습니다. 현재 적용 중인 기본값은 확인할 수 있습니다.',
+ modelGroup: '모델',
+ webSearchGroup: '웹 검색',
+ unsetPlaceholder: '설정 안 함(시스템 기본값)',
+ followChatPlaceholder: '설정 안 함(기본 대화 모델 따름)',
+ slots: {
+ chat: {
+ label: '기본 대화 모델',
+ description: '새 에이전트와 Q&A에서 사용하며, 백그라운드 작업의 대체 모델로도 쓰입니다.',
+ none: '사용 가능한 대화 모델이 없어 Q&A와 백그라운드 생성을 사용할 수 없습니다.',
+ },
+ utility: {
+ label: '경량 생성 모델',
+ description: '세션 제목, MCP 사용 안내, 기억 추출 같은 짧은 텍스트 작업에 사용합니다. 더 빠르고 저렴한 모델을 권장합니다.',
+ none: '사용 가능한 대화 모델이 없어 제목과 안내를 생성할 수 없습니다.',
+ },
+ embedding: {
+ label: '기본 Embedding 모델',
+ description: '새 지식베이스를 만들 때 기본으로 선택됩니다. 기존 지식베이스에는 영향이 없습니다.',
+ none: '사용 가능한 Embedding 모델이 없어 지식베이스를 만들 수 없습니다.',
+ },
+ rerank: {
+ label: '기본 Rerank 모델',
+ description: '자체 재정렬 모델이 없는 검색과 내장 에이전트에서 사용합니다.',
+ none: '사용 가능한 Rerank 모델이 없어 검색 결과가 검색 순서대로 반환됩니다.',
+ },
+ vlm: {
+ label: '기본 비전 모델',
+ description: '이미지 이해와 멀티모달 파싱의 기본 선택입니다.',
+ none: '사용 가능한 비전 모델이 없어 이미지 이해를 사용할 수 없습니다.',
+ },
+ asr: {
+ label: '기본 음성 인식 모델',
+ description: '오디오·비디오 전사의 기본 선택입니다.',
+ none: '사용 가능한 음성 인식 모델이 없어 전사를 사용할 수 없습니다.',
+ },
+ },
+ hints: {
+ workspace: '워크스페이스 설정을 사용 중입니다.',
+ system: '설정 안 됨. 현재 시스템 기본값 사용 중: {name}',
+ auto: '설정 안 됨. 현재 첫 번째 사용 가능 모델 사용 중: {name}',
+ followChat: '설정 안 됨. 기본 대화 모델을 따릅니다: {name}',
+ staleFallback: '선택한 모델이 삭제되었거나 사용할 수 없습니다. 현재 대체 모델: {name}',
+ staleNone: '선택한 모델이 삭제되었거나 사용할 수 없으며, 대체할 모델도 없습니다.',
+ },
+ webSearch: {
+ label: '기본 검색 엔진',
+ description: '자체 검색 엔진이 없는 에이전트에서 웹 검색을 켜면 사용합니다.',
+ unset: '기본 검색 엔진이 없습니다. 자체 검색 엔진이 없는 에이전트는 웹 검색을 할 수 없습니다.',
+ placeholder: '검색 엔진 선택',
+ },
+ toasts: {
+ saveSuccess: '기본 설정을 저장했습니다',
+ saveFailed: '저장 실패: {message}',
+ },
+ },
memoryWorkspaceSettings: {
title: '장기 기억',
description: '구성원이 말한 개인 정보, 선호, 사실, 진행 중인 일을 어시스턴트가 대화를 넘어 기억하도록 합니다.',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index f98b670b9..10badc1c8 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -6953,6 +6953,68 @@ export default {
clearSuccess: 'Ваше значение удалено.',
updatedAt: 'Вы задали это {time}'
},
+ defaultSettings: {
+ loadFailed: 'Не удалось загрузить настройки по умолчанию. Повторите попытку перед редактированием.',
+ title: 'Значения по умолчанию',
+ description: 'Модели и поисковая система, которые функции этого пространства используют по умолчанию, в одном месте.',
+ introTitle: 'Применяются, если ресурс не выбрал своё значение',
+ introDescription: 'Модель, выбранная в агенте, базе знаний или диалоге, всегда в приоритете. Иначе применяется значение пространства отсюда, а если оно не задано — встроенная модель развёртывания.',
+ readOnly: 'Изменять может только администратор пространства. Вы можете посмотреть, какие значения действуют сейчас.',
+ modelGroup: 'Модели',
+ webSearchGroup: 'Веб-поиск',
+ unsetPlaceholder: 'Не задано (системное значение)',
+ followChatPlaceholder: 'Не задано (как модель чата по умолчанию)',
+ slots: {
+ chat: {
+ label: 'Модель чата по умолчанию',
+ description: 'Используется новыми агентами и в вопросах-ответах, а также как резервная для фоновых задач.',
+ none: 'Нет доступной модели чата: вопросы-ответы и фоновая генерация не будут работать.',
+ },
+ utility: {
+ label: 'Лёгкая модель генерации',
+ description: 'Для коротких задач: заголовки сессий, инструкции к сервисам MCP, извлечение памяти. Подойдёт более быстрая и дешёвая модель.',
+ none: 'Нет доступной модели чата: заголовки и инструкции не будут генерироваться.',
+ },
+ embedding: {
+ label: 'Модель эмбеддингов по умолчанию',
+ description: 'Выбирается по умолчанию при создании базы знаний. Существующие базы не меняются.',
+ none: 'Нет доступной модели эмбеддингов: создать базу знаний нельзя.',
+ },
+ rerank: {
+ label: 'Модель реранжирования по умолчанию',
+ description: 'Для поиска и встроенных агентов без собственной модели реранжирования.',
+ none: 'Нет доступной модели реранжирования: результаты возвращаются в порядке извлечения.',
+ },
+ vlm: {
+ label: 'Модель зрения по умолчанию',
+ description: 'Выбор по умолчанию для понимания изображений и мультимодального разбора.',
+ none: 'Нет доступной модели зрения: понимание изображений недоступно.',
+ },
+ asr: {
+ label: 'Модель распознавания речи по умолчанию',
+ description: 'Выбор по умолчанию для транскрипции аудио и видео.',
+ none: 'Нет доступной модели распознавания речи: транскрипция недоступна.',
+ },
+ },
+ hints: {
+ workspace: 'Используется настройка пространства.',
+ system: 'Не задано. Сейчас используется системное значение: {name}',
+ auto: 'Не задано. Сейчас используется первая доступная модель: {name}',
+ followChat: 'Не задано. Как модель чата по умолчанию: {name}',
+ staleFallback: 'Выбранная модель удалена или недоступна. Сейчас используется: {name}',
+ staleNone: 'Выбранная модель удалена или недоступна, и заменить её нечем.',
+ },
+ webSearch: {
+ label: 'Поисковая система по умолчанию',
+ description: 'Используется, когда у агента включён веб-поиск, но не выбрана своя поисковая система.',
+ unset: 'Поисковая система по умолчанию не задана. Агенты без своей поисковой системы не смогут искать в интернете.',
+ placeholder: 'Выберите поисковую систему',
+ },
+ toasts: {
+ saveSuccess: 'Значения по умолчанию сохранены',
+ saveFailed: 'Не удалось сохранить: {message}',
+ },
+ },
memoryWorkspaceSettings: {
title: 'Долговременная память',
description: 'Позволяет ассистенту помнить между разговорами то, что говорят участники: кто они, как предпочитают работать, устойчивые факты и текущие задачи.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 8cdfb17ba..45ea4a893 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6954,6 +6954,68 @@ export default {
clearSuccess: '已清除你的值。',
updatedAt: '你于 {time} 设置'
},
+ defaultSettings: {
+ loadFailed: '默认设置加载失败,请重试后再编辑。',
+ title: '默认配置',
+ description: '集中管理本空间各项功能默认使用的模型和搜索引擎。',
+ introTitle: '资源未单独指定时使用这里的默认值',
+ introDescription: '智能体、知识库或单次对话明确选择的模型优先;没有选择时使用这里的空间默认;空间也没设置时,使用部署内置的默认模型。',
+ readOnly: '仅空间管理员可以修改,你可以查看当前生效的默认值。',
+ modelGroup: '模型',
+ webSearchGroup: '网络搜索',
+ unsetPlaceholder: '未设置(使用系统默认)',
+ followChatPlaceholder: '未设置(跟随默认对话模型)',
+ slots: {
+ chat: {
+ label: '默认对话模型',
+ description: '新建智能体和问答默认使用,也作为后台任务的兜底模型。',
+ none: '空间内没有可用的对话模型,问答和后台生成将无法使用。',
+ },
+ utility: {
+ label: '轻量生成模型',
+ description: '用于生成会话标题、MCP 服务使用说明、记忆提取等短文本任务,可选更快更便宜的模型。',
+ none: '空间内没有可用的对话模型,标题和说明生成将无法使用。',
+ },
+ embedding: {
+ label: '默认 Embedding 模型',
+ description: '新建知识库时默认选用。已有知识库不受影响。',
+ none: '空间内没有可用的 Embedding 模型,无法新建知识库。',
+ },
+ rerank: {
+ label: '默认 Rerank 模型',
+ description: '未单独配置重排模型的检索和内置智能体使用。',
+ none: '空间内没有可用的 Rerank 模型,检索将按召回顺序返回。',
+ },
+ vlm: {
+ label: '默认视觉模型',
+ description: '用于图片理解和多模态解析的默认选择。',
+ none: '空间内没有可用的视觉模型,图片理解不可用。',
+ },
+ asr: {
+ label: '默认语音识别模型',
+ description: '用于音视频转写的默认选择。',
+ none: '空间内没有可用的语音识别模型,音视频转写不可用。',
+ },
+ },
+ hints: {
+ workspace: '使用空间设置。',
+ system: '未设置,当前使用系统默认:{name}',
+ auto: '未设置,当前自动使用首个可用模型:{name}',
+ followChat: '未设置,跟随默认对话模型:{name}',
+ staleFallback: '所选模型已删除或不可用,当前回退到:{name}',
+ staleNone: '所选模型已删除或不可用,且没有可回退的模型。',
+ },
+ webSearch: {
+ label: '默认搜索引擎',
+ description: '未单独指定搜索引擎的智能体开启联网搜索时使用。',
+ unset: '未设置默认搜索引擎,未单独指定搜索引擎的智能体将无法联网搜索。',
+ placeholder: '选择搜索引擎',
+ },
+ toasts: {
+ saveSuccess: '默认配置已保存',
+ saveFailed: '保存失败:{message}',
+ },
+ },
memoryWorkspaceSettings: {
title: '长期记忆',
description: '让助手跨会话记住成员说过的个人信息、偏好、事实与在办事项。',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 59493dca7..e65f0a4c5 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -6954,6 +6954,68 @@ export default {
clearSuccess: '已清除你的值。',
updatedAt: '你於 {time} 設定'
},
+ defaultSettings: {
+ loadFailed: '預設設定載入失敗,請重試後再編輯。',
+ title: '預設設定',
+ description: '集中管理本空間各項功能預設使用的模型和搜尋引擎。',
+ introTitle: '資源未單獨指定時使用這裡的預設值',
+ introDescription: '智慧體、知識庫或單次對話明確選擇的模型優先;未選擇時使用這裡的空間預設;空間也未設定時,使用部署內建的預設模型。',
+ readOnly: '僅空間管理員可以修改,你可以查看目前生效的預設值。',
+ modelGroup: '模型',
+ webSearchGroup: '網路搜尋',
+ unsetPlaceholder: '未設定(使用系統預設)',
+ followChatPlaceholder: '未設定(跟隨預設對話模型)',
+ slots: {
+ chat: {
+ label: '預設對話模型',
+ description: '新建智慧體和問答預設使用,也作為背景任務的備援模型。',
+ none: '空間內沒有可用的對話模型,問答和背景生成將無法使用。',
+ },
+ utility: {
+ label: '輕量生成模型',
+ description: '用於生成會話標題、MCP 服務使用說明、記憶擷取等短文字任務,可選更快更便宜的模型。',
+ none: '空間內沒有可用的對話模型,標題和說明生成將無法使用。',
+ },
+ embedding: {
+ label: '預設 Embedding 模型',
+ description: '新建知識庫時預設選用。既有知識庫不受影響。',
+ none: '空間內沒有可用的 Embedding 模型,無法新建知識庫。',
+ },
+ rerank: {
+ label: '預設 Rerank 模型',
+ description: '未單獨設定重排模型的檢索和內建智慧體使用。',
+ none: '空間內沒有可用的 Rerank 模型,檢索將依召回順序返回。',
+ },
+ vlm: {
+ label: '預設視覺模型',
+ description: '用於圖片理解和多模態解析的預設選擇。',
+ none: '空間內沒有可用的視覺模型,圖片理解不可用。',
+ },
+ asr: {
+ label: '預設語音辨識模型',
+ description: '用於影音轉寫的預設選擇。',
+ none: '空間內沒有可用的語音辨識模型,影音轉寫不可用。',
+ },
+ },
+ hints: {
+ workspace: '使用空間設定。',
+ system: '未設定,目前使用系統預設:{name}',
+ auto: '未設定,目前自動使用第一個可用模型:{name}',
+ followChat: '未設定,跟隨預設對話模型:{name}',
+ staleFallback: '所選模型已刪除或不可用,目前回退到:{name}',
+ staleNone: '所選模型已刪除或不可用,且沒有可回退的模型。',
+ },
+ webSearch: {
+ label: '預設搜尋引擎',
+ description: '未單獨指定搜尋引擎的智慧體開啟聯網搜尋時使用。',
+ unset: '未設定預設搜尋引擎,未單獨指定搜尋引擎的智慧體將無法聯網搜尋。',
+ placeholder: '選擇搜尋引擎',
+ },
+ toasts: {
+ saveSuccess: '預設設定已儲存',
+ saveFailed: '儲存失敗:{message}',
+ },
+ },
memoryWorkspaceSettings: {
title: '長期記憶',
description: '讓助手跨會話記住成員說過的個人資料、偏好、事實與在辦事項。',
diff --git a/frontend/src/utils/modelDefaults.test.ts b/frontend/src/utils/modelDefaults.test.ts
new file mode 100644
index 000000000..4416ec3a3
--- /dev/null
+++ b/frontend/src/utils/modelDefaults.test.ts
@@ -0,0 +1,29 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { isDefaultModelForType, selectInitialModelId } from './modelDefaults'
+
+test('creation picks independent vision, chat and ASR defaults', () => {
+ const models = [
+ { id: 'chat', type: 'KnowledgeQA', is_default: true, parameters: { supports_vision: true } },
+ { id: 'vision', type: 'KnowledgeQA', default_for: ['VLLM'], parameters: { supports_vision: true } },
+ { id: 'asr-first', type: 'ASR' },
+ { id: 'asr-default', type: 'ASR', is_default: true },
+ ]
+ assert.equal(selectInitialModelId(models, 'KnowledgeQA'), 'chat')
+ assert.equal(selectInitialModelId(models, 'VLLM'), 'vision')
+ assert.equal(selectInitialModelId(models, 'ASR'), 'asr-default')
+ assert.equal(isDefaultModelForType(models[0], 'VLLM'), false)
+ assert.equal(isDefaultModelForType(models[1], 'VLLM'), true)
+ assert.equal(isDefaultModelForType(models[1], 'KnowledgeQA'), false)
+})
+
+test('vision fallback prefers a native default and skips unavailable models', () => {
+ const models = [
+ { id: 'chat', type: 'KnowledgeQA', is_default: true, parameters: { supports_vision: true } },
+ { id: 'inactive', type: 'VLLM', default_for: ['VLLM'], status: 'downloading' },
+ { id: 'native', type: 'VLLM', is_default: true },
+ ]
+ assert.equal(selectInitialModelId(models, 'VLLM'), 'native')
+ assert.equal(selectInitialModelId(models.slice(0, 2), 'VLLM'), 'chat')
+ assert.equal(selectInitialModelId(models, 'ASR'), null)
+})
diff --git a/frontend/src/utils/modelDefaults.ts b/frontend/src/utils/modelDefaults.ts
index 203c0fbaa..7ac2212a2 100644
--- a/frontend/src/utils/modelDefaults.ts
+++ b/frontend/src/utils/modelDefaults.ts
@@ -3,6 +3,17 @@ export interface ModelDefaultCandidate {
type: string
status?: string
is_default?: boolean
+ default_for?: string[]
+ parameters?: { supports_vision?: boolean }
+}
+
+export function modelSupportsType(model: ModelDefaultCandidate, modelType: string): boolean {
+ return model.type === modelType
+ || (modelType === 'VLLM' && model.type === 'KnowledgeQA' && model.parameters?.supports_vision === true)
+}
+
+export function isDefaultModelForType(model: ModelDefaultCandidate, modelType: string): boolean {
+ return Boolean(model.default_for?.includes(modelType) || (model.type === modelType && model.is_default))
}
/**
@@ -15,8 +26,11 @@ export function selectInitialModelId(
): string | null {
const active = models.filter(
model => Boolean(model.id?.trim())
- && model.type === modelType
+ && modelSupportsType(model, modelType)
&& (!model.status || model.status === 'active'),
)
- return active.find(model => model.is_default)?.id?.trim() ?? active[0]?.id?.trim() ?? null
+ const chosen = active.find(model => model.default_for?.includes(modelType))
+ ?? active.find(model => isDefaultModelForType(model, modelType))
+ ?? active[0]
+ return chosen?.id?.trim() ?? null
}
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index c9d0f2ab7..e6b20bb02 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -3034,12 +3034,20 @@ const applyDefaultModelsIfEmpty = () => {
if (props.mode !== 'create' || !formData.value) return
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
const rerankModelId = selectInitialModelId(allModels.value, 'Rerank')
+ const vlmModelId = selectInitialModelId(allModels.value, 'VLLM')
+ const asrModelId = selectInitialModelId(allModels.value, 'ASR')
if (!formData.value.config.model_id && chatModelId) {
formData.value.config.model_id = chatModelId
}
if (!formData.value.config.rerank_model_id && rerankModelId) {
formData.value.config.rerank_model_id = rerankModelId
}
+ if (!formData.value.config.vlm_model_id && vlmModelId) {
+ formData.value.config.vlm_model_id = vlmModelId
+ }
+ if (!formData.value.config.asr_model_id && asrModelId) {
+ formData.value.config.asr_model_id = asrModelId
+ }
}
const agentMode = computed({
diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
index 611a55d4e..12f7845a4 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
@@ -907,12 +907,20 @@ const applyDefaultModelsIfEmpty = () => {
if (!formData.value || editorMode.value !== 'create') return
const chatModelId = selectInitialModelId(allModels.value, 'KnowledgeQA')
const embeddingModelId = selectInitialModelId(allModels.value, 'Embedding')
+ const vlmModelId = selectInitialModelId(allModels.value, 'VLLM')
+ const asrModelId = selectInitialModelId(allModels.value, 'ASR')
if (!formData.value.modelConfig.llmModelId && chatModelId) {
formData.value.modelConfig.llmModelId = chatModelId
}
if (!formData.value.modelConfig.embeddingModelId && embeddingModelId) {
formData.value.modelConfig.embeddingModelId = embeddingModelId
}
+ if (!formData.value.multimodalConfig.vllmModelId && vlmModelId) {
+ formData.value.multimodalConfig.vllmModelId = vlmModelId
+ }
+ if (!formData.value.asrConfig.modelId && asrModelId) {
+ formData.value.asrConfig.modelId = asrModelId
+ }
}
watch(
@@ -1982,6 +1990,7 @@ watch(
watch(() => chatResources.allModels, (list) => {
if (props.visible) {
allModels.value = list || []
+ applyDefaultModelsIfEmpty()
}
})
</script>
diff --git a/frontend/src/views/settings/DefaultSettings.test.ts b/frontend/src/views/settings/DefaultSettings.test.ts
new file mode 100644
index 000000000..8ac258747
--- /dev/null
+++ b/frontend/src/views/settings/DefaultSettings.test.ts
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict'
+import test, { type TestContext } from 'node:test'
+import { reactive } from 'vue'
+import { fixture, flush } from '../../test-utils/vueFixture'
+import { isTenantWebSearchReady } from '../../utils/agentWebSearch'
+import type { DefaultSettings } from '../../api/default-settings'
+import type { WebSearchProviderEntity } from '../../api/web-search-provider'
+
+const initial: DefaultSettings = {
+ chat_model_id: 'chat', utility_model_id: 'utility', embedding_model_id: 'embed',
+ rerank_model_id: 'rerank', vlm_model_id: 'vision', asr_model_id: 'asr',
+}
+
+function setup(t: TestContext, read = async () => ({ data: { ...initial } })) {
+ const f = fixture(t)
+ const api = {
+ getTenantDefaultSettings: t.mock.fn(read),
+ updateTenantDefaultSettings: t.mock.fn(async (_settings: DefaultSettings) => ({})),
+ patchWebSearchProvider: t.mock.fn(async (_id: string, _patch: { is_default: boolean }) => ({})),
+ }
+ const store = reactive({
+ allModels: [], webSearchProviders: [{ id: 'search', name: 'Search', is_default: false }] as WebSearchProviderEntity[],
+ ensureModels: t.mock.fn(async (_force?: boolean) => {}),
+ ensureWebSearchProviders: t.mock.fn(async (_force?: boolean) => {}),
+ })
+ const { vm } = f.component(new URL('./DefaultSettings.vue', import.meta.url), {
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
+ 'tdesign-vue-next': { MessagePlugin: { success() {}, error() {} } },
+ '@/api/default-settings': api,
+ '@/api/web-search-provider': api,
+ '@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
+ '@/stores/ui': { useUIStore: () => ({}) },
+ '@/stores/chatResources': { useChatResourcesStore: () => store },
+ '@/stores/deploymentCapabilities': { useDeploymentCapabilitiesStore: () => ({ isSupported: () => true }) },
+ })
+ return { vm, store, api }
+}
+
+test('blocks saves until all persisted slots have loaded', async t => {
+ let resolve!: (value: { data: DefaultSettings }) => void
+ const { vm, api } = setup(t, () => new Promise(done => { resolve = done }))
+ assert.equal(vm.settingsLoaded, false)
+ await vm.onModelChange('chat_model_id', 'new-chat')
+ assert.equal(api.updateTenantDefaultSettings.mock.callCount(), 0)
+ resolve({ data: initial })
+ await flush()
+ assert.equal(vm.settingsLoaded, true)
+ await vm.onModelChange('chat_model_id', 'new-chat')
+ const saved = api.updateTenantDefaultSettings.mock.calls[0].arguments[0]
+ assert.deepEqual({ ...saved }, { ...initial, chat_model_id: 'new-chat' })
+})
+
+test('a failed initial load stays read-only until a successful retry', async t => {
+ const { vm, api } = setup(t, async () => { throw new Error('offline') })
+ await flush()
+ assert.equal(vm.settingsLoadFailed, true)
+ await vm.onModelChange('chat_model_id', 'new-chat')
+ assert.equal(api.updateTenantDefaultSettings.mock.callCount(), 0)
+ api.getTenantDefaultSettings.mock.mockImplementation(async () => ({ data: initial }))
+ await vm.loadSettings()
+ assert.equal(vm.settingsLoaded, true)
+ assert.equal(vm.settingsLoadFailed, false)
+ await vm.onModelChange('chat_model_id', 'new-chat')
+ assert.equal(api.updateTenantDefaultSettings.mock.callCount(), 1)
+})
+
+test('does not roll back a saved setting when model refresh fails', async t => {
+ const { vm, api, store } = setup(t)
+ await flush()
+ store.ensureModels.mock.mockImplementation(async () => { throw new Error('offline') })
+ await vm.onModelChange('chat_model_id', 'new-chat')
+ assert.equal(api.updateTenantDefaultSettings.mock.callCount(), 1)
+ assert.equal(vm.settings.chat_model_id, 'new-chat')
+})
+
+test('saving and clearing web search updates the state consumed by chat', async t => {
+ const { vm, api, store } = setup(t)
+ await flush()
+ assert.equal(isTenantWebSearchReady(store.webSearchProviders), false)
+ await vm.onWebSearchChange('search')
+ assert.equal(isTenantWebSearchReady(store.webSearchProviders), true)
+ assert.equal(vm.webSearchDefaultId, 'search')
+ await vm.onWebSearchChange('')
+ assert.equal(isTenantWebSearchReady(store.webSearchProviders), false)
+ assert.equal(api.patchWebSearchProvider.mock.callCount(), 2)
+ assert.equal(store.ensureWebSearchProviders.mock.callCount(), 3)
+})
diff --git a/frontend/src/views/settings/DefaultSettings.vue b/frontend/src/views/settings/DefaultSettings.vue
new file mode 100644
index 000000000..b6ba85e87
--- /dev/null
+++ b/frontend/src/views/settings/DefaultSettings.vue
@@ -0,0 +1,354 @@
+<template>
+ <div class="default-settings">
+ <div class="section-header">
+ <h2>{{ t('defaultSettings.title') }}</h2>
+ <p class="section-description">{{ t('defaultSettings.description') }}</p>
+ </div>
+
+ <div class="intro">
+ <t-icon name="info-circle" class="intro-icon" />
+ <div>
+ <p class="intro-title">{{ t('defaultSettings.introTitle') }}</p>
+ <p class="intro-desc">{{ t('defaultSettings.introDescription') }}</p>
+ <p v-if="!canEdit" class="intro-desc readonly">{{ t('defaultSettings.readOnly') }}</p>
+ </div>
+ </div>
+
+ <h3 class="group-title">{{ t('defaultSettings.modelGroup') }}</h3>
+ <t-alert v-if="settingsLoadFailed" theme="error" :message="t('defaultSettings.loadFailed')">
+ <template #operation>
+ <t-button variant="text" @click="loadSettings">{{ t('common.retry') }}</t-button>
+ </template>
+ </t-alert>
+ <div class="settings-group">
+ <div v-for="slot in modelSlots" :key="slot.field" class="setting-row">
+ <div class="setting-info">
+ <label>{{ t(`defaultSettings.slots.${slot.key}.label`) }}</label>
+ <p class="desc">{{ t(`defaultSettings.slots.${slot.key}.description`) }}</p>
+ <p v-if="settingsLoaded" class="desc hint" :class="{ warn: effective[slot.field].stale || effective[slot.field].source === 'none' }">
+ {{ effectiveHint(slot, effective[slot.field]) }}
+ </p>
+ </div>
+ <div class="setting-control model-control">
+ <ModelSelector
+ :model-type="slot.type"
+ :selected-model-id="settings[slot.field]"
+ :disabled="!canEdit || saving || !settingsLoaded"
+ :all-models="models"
+ :clearable="true"
+ :placeholder="slotPlaceholder(slot)"
+ @update:selected-model-id="(id: string) => onModelChange(slot.field, id)"
+ @add-model="openModels(slot.type)"
+ />
+ </div>
+ </div>
+ </div>
+
+ <template v-if="webSearchSupported">
+ <h3 class="group-title">{{ t('defaultSettings.webSearchGroup') }}</h3>
+ <div class="settings-group">
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('defaultSettings.webSearch.label') }}</label>
+ <p class="desc">{{ t('defaultSettings.webSearch.description') }}</p>
+ <p v-if="!webSearchDefaultId" class="desc hint warn">{{ t('defaultSettings.webSearch.unset') }}</p>
+ </div>
+ <div class="setting-control model-control">
+ <t-select
+ :value="webSearchDefaultId"
+ :options="webSearchOptions"
+ :disabled="!canEdit || saving || webSearchLoading"
+ :loading="webSearchLoading"
+ :placeholder="t('defaultSettings.webSearch.placeholder')"
+ clearable
+ style="width: 100%"
+ @change="onWebSearchChange"
+ />
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, onMounted, reactive, ref } from 'vue'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+import ModelSelector from '@/components/ModelSelector.vue'
+import type { ModelConfig } from '@/api/model'
+import {
+ getTenantDefaultSettings,
+ updateTenantDefaultSettings,
+ type DefaultSettings,
+} from '@/api/default-settings'
+import { patchWebSearchProvider } from '@/api/web-search-provider'
+import { useAuthStore } from '@/stores/auth'
+import { useUIStore } from '@/stores/ui'
+import { useChatResourcesStore } from '@/stores/chatResources'
+import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
+import {
+ effectiveModelDefault,
+ effectiveUtilityDefault,
+ type DefaultModelType,
+ type EffectiveDefault,
+} from './defaultSettingsState'
+
+type ModelField = keyof DefaultSettings
+
+interface ModelSlot {
+ field: ModelField
+ key: string
+ type: DefaultModelType
+}
+
+const modelSlots: ModelSlot[] = [
+ { field: 'chat_model_id', key: 'chat', type: 'KnowledgeQA' },
+ { field: 'utility_model_id', key: 'utility', type: 'KnowledgeQA' },
+ { field: 'embedding_model_id', key: 'embedding', type: 'Embedding' },
+ { field: 'rerank_model_id', key: 'rerank', type: 'Rerank' },
+ { field: 'vlm_model_id', key: 'vlm', type: 'VLLM' },
+ { field: 'asr_model_id', key: 'asr', type: 'ASR' },
+]
+
+const { t } = useI18n()
+const authStore = useAuthStore()
+const uiStore = useUIStore()
+const chatResources = useChatResourcesStore()
+const deploymentCapabilities = useDeploymentCapabilitiesStore()
+
+const canEdit = computed(() => authStore.hasRole('admin'))
+const saving = ref(false)
+const settingsLoaded = ref(false)
+const settingsLoadFailed = ref(false)
+
+const settings = reactive<DefaultSettings>({
+ chat_model_id: '',
+ utility_model_id: '',
+ embedding_model_id: '',
+ rerank_model_id: '',
+ vlm_model_id: '',
+ asr_model_id: '',
+})
+
+const models = computed<ModelConfig[]>(() => chatResources.allModels.filter((m) => m.status === 'active'))
+
+const effective = computed(() => {
+ const out = {} as Record<ModelField, EffectiveDefault<ModelConfig>>
+ for (const slot of modelSlots) {
+ out[slot.field] = slot.field === 'utility_model_id'
+ ? effectiveUtilityDefault(models.value, settings.utility_model_id, settings.chat_model_id)
+ : effectiveModelDefault(models.value, slot.type, settings[slot.field])
+ }
+ return out
+})
+
+const modelName = (model: ModelConfig | null) => model?.display_name?.trim() || model?.name || ''
+
+const effectiveHint = (slot: ModelSlot, state: EffectiveDefault<ModelConfig>) => {
+ const name = modelName(state.model)
+ if (state.stale) {
+ return state.model
+ ? t('defaultSettings.hints.staleFallback', { name })
+ : t('defaultSettings.hints.staleNone')
+ }
+ switch (state.source) {
+ case 'workspace':
+ return t('defaultSettings.hints.workspace')
+ case 'system':
+ return t('defaultSettings.hints.system', { name })
+ case 'auto':
+ return t('defaultSettings.hints.auto', { name })
+ case 'chat':
+ return t('defaultSettings.hints.followChat', { name })
+ default:
+ return t(`defaultSettings.slots.${slot.key}.none`)
+ }
+}
+
+const slotPlaceholder = (slot: ModelSlot) =>
+ slot.field === 'utility_model_id'
+ ? t('defaultSettings.followChatPlaceholder')
+ : t('defaultSettings.unsetPlaceholder')
+
+const loadSettings = async () => {
+ settingsLoaded.value = false
+ settingsLoadFailed.value = false
+ try {
+ const response = await getTenantDefaultSettings()
+ if (!response.data) throw new Error('Default settings response is missing data')
+ for (const slot of modelSlots) {
+ settings[slot.field] = response.data[slot.field] || ''
+ }
+ settingsLoaded.value = true
+ } catch (error) {
+ settingsLoadFailed.value = true
+ console.error('Failed to load default settings:', error)
+ }
+}
+
+const onModelChange = async (field: ModelField, id: string) => {
+ if (!canEdit.value || !settingsLoaded.value || saving.value || settings[field] === (id || '')) return
+ const previous = settings[field]
+ settings[field] = id || ''
+ saving.value = true
+ try {
+ await updateTenantDefaultSettings({ ...settings })
+ // Refresh every picker. A failed refresh must not undo an already saved choice.
+ await chatResources.ensureModels(true).catch((error) => {
+ console.error('Failed to refresh models after saving defaults:', error)
+ })
+ MessagePlugin.success(t('defaultSettings.toasts.saveSuccess'))
+ } catch (error: any) {
+ settings[field] = previous
+ MessagePlugin.error(t('defaultSettings.toasts.saveFailed', { message: error?.message || '' }))
+ } finally {
+ saving.value = false
+ }
+}
+
+const webSearchSupported = computed(() => deploymentCapabilities.isSupported('settings.websearch'))
+const webSearchProviders = computed(() => chatResources.webSearchProviders)
+const webSearchLoading = ref(false)
+
+const webSearchDefaultId = computed(() => webSearchProviders.value.find((p) => p.is_default)?.id || '')
+const webSearchOptions = computed(() =>
+ webSearchProviders.value
+ .filter((p) => p.id)
+ .map((p) => ({ label: p.name, value: p.id as string })),
+)
+
+const loadWebSearchProviders = async () => {
+ webSearchLoading.value = true
+ try {
+ await chatResources.ensureWebSearchProviders(true)
+ } catch (error) {
+ console.error('Failed to load web search providers:', error)
+ } finally {
+ webSearchLoading.value = false
+ }
+}
+
+// Providers keep their own is_default flag; setting one clears the others
+// on the server, so clearing is the only case that targets the old default.
+const onWebSearchChange = async (value: unknown) => {
+ const id = typeof value === 'string' ? value : ''
+ const current = webSearchDefaultId.value
+ if (!canEdit.value || saving.value || webSearchLoading.value || id === current) return
+ saving.value = true
+ try {
+ if (id) {
+ await patchWebSearchProvider(id, { is_default: true })
+ } else if (current) {
+ await patchWebSearchProvider(current, { is_default: false })
+ }
+ for (const provider of webSearchProviders.value) {
+ provider.is_default = provider.id === id
+ }
+ await loadWebSearchProviders()
+ MessagePlugin.success(t('defaultSettings.toasts.saveSuccess'))
+ } catch (error: any) {
+ MessagePlugin.error(t('defaultSettings.toasts.saveFailed', { message: error?.message || '' }))
+ } finally {
+ saving.value = false
+ }
+}
+
+const openModels = (type: DefaultModelType) => {
+ const subsection = type === 'KnowledgeQA' ? 'chat' : type === 'VLLM' ? 'vllm' : type.toLowerCase()
+ uiStore.openSettings('models', subsection)
+ window.dispatchEvent(
+ new CustomEvent('settings-nav', { detail: { section: 'models', subsection } }),
+ )
+}
+
+onMounted(() => {
+ void chatResources.ensureModels(true).catch(() => {})
+ void loadSettings()
+ if (webSearchSupported.value) void loadWebSearchProviders()
+})
+</script>
+
+<style lang="less" scoped>
+@import (reference) '@/components/css/settings-section.less';
+
+.default-settings {
+ width: 100%;
+}
+
+.section-header {
+ .settings-section-header();
+}
+
+.intro {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 14px 16px;
+ margin-bottom: 8px;
+ border-radius: var(--app-radius-md);
+ background: var(--td-bg-color-secondarycontainer);
+}
+
+.intro-icon {
+ color: var(--td-brand-color);
+ margin-top: 2px;
+ flex-shrink: 0;
+}
+
+.intro-title {
+ margin: 0 0 4px 0;
+ font-size: var(--app-text-base);
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+}
+
+.intro-desc {
+ margin: 0;
+ font-size: var(--app-text-md);
+ line-height: 1.6;
+ color: var(--td-text-color-secondary);
+
+ &.readonly {
+ margin-top: 6px;
+ color: var(--td-warning-color);
+ }
+}
+
+.group-title {
+ margin: 24px 0 0;
+ font-size: var(--app-text-base);
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+}
+
+.settings-group {
+ display: flex;
+ flex-direction: column;
+}
+
+.setting-row {
+ .setting-row();
+}
+
+.setting-info {
+ .setting-info();
+
+ .hint {
+ margin-top: 4px !important;
+ color: var(--td-text-color-placeholder);
+
+ &.warn {
+ color: var(--td-warning-color);
+ }
+ }
+}
+
+.setting-control {
+ .setting-control();
+}
+
+.model-control {
+ min-width: 280px;
+}
+</style>
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index 8e4a4c875..dd68ba4cb 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -106,6 +106,11 @@
<ChatHistorySettings />
</div>
+ <!-- 默认配置(空间级默认模型与搜索引擎) -->
+ <div v-if="currentSection === 'defaults'" class="section">
+ <DefaultSettings />
+ </div>
+
<!-- 长期记忆(空间级开关) -->
<div v-if="currentSection === 'memory'" class="section">
<MemoryWorkspaceSettings />
@@ -223,6 +228,7 @@ import ChatHistorySettings from './ChatHistorySettings.vue'
import MemorySettings from './MemorySettings.vue'
import EnvVarSettings from './EnvVarSettings.vue'
import MemoryWorkspaceSettings from './MemoryWorkspaceSettings.vue'
+import DefaultSettings from './DefaultSettings.vue'
import AssistantSettings from './AssistantSettings.vue'
import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
@@ -367,6 +373,7 @@ const navItems = computed(() => {
{ key: 'models', icon: 'control-platform', label: t('settings.modelManagement') },
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') },
+ { key: 'defaults', icon: 'setting-1', label: t('defaultSettings.title') },
{ key: 'memory', icon: 'bulletpoint', label: t('memoryWorkspaceSettings.title') },
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
@@ -411,7 +418,7 @@ const navGroups = computed<NavGroup[]>(() => {
{
key: 'workspace',
label: t('settings.navGroups.workspace'),
- items: pickItems(['tenant', 'members', 'chathistory', 'memory']),
+ items: pickItems(['tenant', 'members', 'defaults', 'chathistory', 'memory']),
},
{
key: 'models_runtime',
diff --git a/frontend/src/views/settings/defaultSettingsState.test.ts b/frontend/src/views/settings/defaultSettingsState.test.ts
new file mode 100644
index 000000000..be15527a3
--- /dev/null
+++ b/frontend/src/views/settings/defaultSettingsState.test.ts
@@ -0,0 +1,64 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { effectiveModelDefault, effectiveUtilityDefault } from './defaultSettingsState'
+
+const models = [
+ { id: 'chat-a', type: 'KnowledgeQA', status: 'active' },
+ { id: 'chat-yaml', type: 'KnowledgeQA', status: 'active', is_default: true },
+ { id: 'chat-down', type: 'KnowledgeQA', status: 'downloading' },
+ { id: 'rerank-a', type: 'Rerank', status: 'active' },
+]
+
+test('a usable workspace choice is the effective default', () => {
+ const got = effectiveModelDefault(models, 'KnowledgeQA', 'chat-a')
+ assert.equal(got.model?.id, 'chat-a')
+ assert.equal(got.source, 'workspace')
+ assert.equal(got.stale, false)
+})
+
+test('an empty slot shows the deployment default', () => {
+ const got = effectiveModelDefault(models, 'KnowledgeQA', '')
+ assert.equal(got.model?.id, 'chat-yaml')
+ assert.equal(got.source, 'system')
+ assert.equal(got.stale, false)
+})
+
+test('an unusable choice is stale and falls back', () => {
+ for (const id of ['gone', 'chat-down', 'rerank-a']) {
+ const got = effectiveModelDefault(models, 'KnowledgeQA', id)
+ assert.equal(got.model?.id, 'chat-yaml', id)
+ assert.equal(got.stale, true, id)
+ }
+})
+
+test('without any default the first usable model is used, else none', () => {
+ const plain = models.map((m) => ({ ...m, is_default: false }))
+ assert.equal(effectiveModelDefault(plain, 'KnowledgeQA', '').source, 'auto')
+ assert.equal(effectiveModelDefault(plain, 'KnowledgeQA', '').model?.id, 'chat-a')
+ assert.equal(effectiveModelDefault(plain, 'Embedding', '').source, 'none')
+})
+
+test('the utility slot follows the chat default when unset or stale', () => {
+ assert.equal(effectiveUtilityDefault(models, 'chat-a', 'chat-yaml').source, 'workspace')
+ const follow = effectiveUtilityDefault(models, '', 'chat-a')
+ assert.equal(follow.model?.id, 'chat-a')
+ assert.equal(follow.source, 'chat')
+ const stale = effectiveUtilityDefault(models, 'gone', '')
+ assert.equal(stale.model?.id, 'chat-yaml')
+ assert.equal(stale.stale, true)
+ assert.equal(effectiveUtilityDefault([], '', '').source, 'none')
+})
+
+test('vision-capable chat choices are usable without inheriting chat default flags', () => {
+ const models = [
+ { id: 'chat', type: 'KnowledgeQA', is_default: true, parameters: { supports_vision: true } },
+ { id: 'native', type: 'VLLM', is_default: true },
+ ]
+ const explicit = effectiveModelDefault(models, 'VLLM', 'chat')
+ assert.equal(explicit.source, 'workspace')
+ assert.equal(explicit.stale, false)
+ assert.equal(explicit.model?.id, 'chat')
+ const fallback = effectiveModelDefault(models, 'VLLM', 'deleted')
+ assert.equal(fallback.model?.id, 'native')
+ assert.equal(fallback.stale, true)
+})
diff --git a/frontend/src/views/settings/defaultSettingsState.ts b/frontend/src/views/settings/defaultSettingsState.ts
new file mode 100644
index 000000000..028ef93a4
--- /dev/null
+++ b/frontend/src/views/settings/defaultSettingsState.ts
@@ -0,0 +1,52 @@
+import { isDefaultModelForType, modelSupportsType, type ModelDefaultCandidate } from '../../utils/modelDefaults'
+
+export type DefaultModelType = 'KnowledgeQA' | 'Embedding' | 'Rerank' | 'VLLM' | 'ASR'
+
+export type DefaultModelLike = ModelDefaultCandidate
+
+// workspace: the slot's own choice. system: the deployment default (a
+// built-in model's is_default). auto: nothing chosen, the first usable model.
+// chat: the utility slot following the chat default.
+export type DefaultSource = 'workspace' | 'system' | 'auto' | 'chat' | 'none'
+
+export interface EffectiveDefault<M extends DefaultModelLike> {
+ model: M | null
+ source: DefaultSource
+ // The slot names a model that is gone, inactive or of another type.
+ stale: boolean
+}
+
+function usable<M extends DefaultModelLike>(model: M, type: DefaultModelType) {
+ return Boolean(model.id?.trim()) && modelSupportsType(model, type) && (!model.status || model.status === 'active')
+}
+
+// Mirrors the backend: the model list already marks the workspace choice as
+// is_default when it is usable, so the fallback only runs for empty or stale
+// slots, where is_default is the deployment default.
+export function effectiveModelDefault<M extends DefaultModelLike>(
+ models: M[],
+ type: DefaultModelType,
+ configuredId: string,
+): EffectiveDefault<M> {
+ const id = configuredId.trim()
+ const chosen = id ? models.find((m) => m.id === id && usable(m, type)) : undefined
+ if (chosen) return { model: chosen, source: 'workspace', stale: false }
+ const stale = id !== ''
+ const candidates = models.filter((m) => usable(m, type))
+ const flagged = candidates.find((m) => m.default_for?.includes(type))
+ ?? candidates.find((m) => isDefaultModelForType(m, type))
+ if (flagged) return { model: flagged, source: 'system', stale }
+ if (candidates[0]) return { model: candidates[0], source: 'auto', stale }
+ return { model: null, source: 'none', stale }
+}
+
+export function effectiveUtilityDefault<M extends DefaultModelLike>(
+ models: M[],
+ utilityId: string,
+ chatId: string,
+): EffectiveDefault<M> {
+ const own = effectiveModelDefault(models, 'KnowledgeQA', utilityId)
+ if (own.source === 'workspace') return own
+ const chat = effectiveModelDefault(models, 'KnowledgeQA', chatId)
+ return { model: chat.model, source: chat.model ? 'chat' : 'none', stale: own.stale }
+}
diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go
index e44612f3a..7730e48c8 100644
--- a/internal/application/service/agent_share.go
+++ b/internal/application/service/agent_share.go
@@ -63,19 +63,10 @@ func agentRequiresRerankModel(agent *types.CustomAgent) bool {
// cannot be configured with one: the workspace's default active rerank
// model, else its first active one, else none.
func pickWorkspaceRerankModelID(models []*types.Model) string {
- first := ""
- for _, model := range models {
- if model == nil || model.Type != types.ModelTypeRerank || model.Status != types.ModelStatusActive {
- continue
- }
- if model.IsDefault {
- return model.ID
- }
- if first == "" {
- first = model.ID
- }
+ if model := types.PickDefaultModel(models, types.ModelTypeRerank); model != nil {
+ return model.ID
}
- return first
+ return ""
}
// isBuiltinAgent guards sharing. Shares of built-in agents created before
diff --git a/internal/application/service/automation_scheduler_timezone_test.go b/internal/application/service/automation_scheduler_timezone_test.go
index 94ad86bd5..0e61064c4 100644
--- a/internal/application/service/automation_scheduler_timezone_test.go
+++ b/internal/application/service/automation_scheduler_timezone_test.go
@@ -107,7 +107,10 @@ func TestAutomationDueTaskStillClaimsUnderUTCClock(t *testing.T) {
runs := f.runs(t, a.ID)
require.Len(t, runs, 1)
- require.Contains(t, []string{types.AutomationRunQueued, types.AutomationRunRunning}, runs[0].Status)
+ // tick starts an asynchronous executor. Wait for it to release its slot
+ // before the fixture closes SQLite and removes its WAL directory.
+ done := f.settleRun(t, runs[0].ID)
+ require.Equal(t, types.AutomationRunSucceeded, done.Status)
reloaded := f.reload(t, a.ID)
require.False(t, reloaded.Enabled)
require.Nil(t, reloaded.NextRunAt)
diff --git a/internal/application/service/evaluation.go b/internal/application/service/evaluation.go
index 4a3844cb4..4ad0d22ef 100644
--- a/internal/application/service/evaluation.go
+++ b/internal/application/service/evaluation.go
@@ -152,22 +152,12 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
return nil, err
}
- var embeddingModelID, llmModelID string
- for _, model := range models {
- if model == nil {
- continue
- }
- if model.Type == types.ModelTypeEmbedding {
- embeddingModelID = model.ID
- }
- if model.Type == types.ModelTypeKnowledgeQA {
- llmModelID = model.ID
- }
- }
-
- if embeddingModelID == "" || llmModelID == "" {
+ embeddingModel := types.PickDefaultModel(models, types.ModelTypeEmbedding)
+ llmModel := types.PickChatModel(models, "")
+ if embeddingModel == nil || llmModel == nil {
return nil, fmt.Errorf("no default models found for evaluation")
}
+ embeddingModelID, llmModelID := embeddingModel.ID, llmModel.ID
kb, err := e.knowledgeBaseService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
Name: "evaluation",
@@ -214,14 +204,8 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
// 获取默认的重排模型
models, err := e.modelService.ListModels(ctx)
if err == nil {
- for _, model := range models {
- if model == nil {
- continue
- }
- if model.Type == types.ModelTypeRerank {
- rerankModelID = model.ID
- break
- }
+ if model := types.PickDefaultModel(models, types.ModelTypeRerank); model != nil {
+ rerankModelID = model.ID
}
}
if rerankModelID == "" {
@@ -235,14 +219,8 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
// 获取默认的LLM模型
models, err := e.modelService.ListModels(ctx)
if err == nil {
- for _, model := range models {
- if model == nil {
- continue
- }
- if model.Type == types.ModelTypeKnowledgeQA {
- chatModelID = model.ID
- break
- }
+ if model := types.PickChatModel(models, ""); model != nil {
+ chatModelID = model.ID
}
}
if chatModelID == "" {
diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go
index a41b38ef6..3cb2bd8b0 100644
--- a/internal/application/service/knowledgebase.go
+++ b/internal/application/service/knowledgebase.go
@@ -549,7 +549,7 @@ func (s *knowledgeBaseService) resolveUpdatedVLMConfig(
if err != nil {
return types.VLMConfig{}, fmt.Errorf("get vlm model %s: %w", next.ModelID, err)
}
- if model.Type != types.ModelTypeVLLM {
+ if !model.SupportsType(types.ModelTypeVLLM) {
return types.VLMConfig{}, apperrors.NewBadRequestError(
fmt.Sprintf("vlm_config.model_id: model type is %s, want %s", model.Type, types.ModelTypeVLLM))
}
diff --git a/internal/application/service/knowledgebase_search_rerank.go b/internal/application/service/knowledgebase_search_rerank.go
index 45008dc32..0705ade3d 100644
--- a/internal/application/service/knowledgebase_search_rerank.go
+++ b/internal/application/service/knowledgebase_search_rerank.go
@@ -48,10 +48,8 @@ func resolveRerankModelID(
logger.Warnf(ctx, "Rerank model auto-detection failed: %v", err)
return "", "", nil
}
- for _, model := range models {
- if model != nil && model.Type == types.ModelTypeRerank {
- return model.ID, types.RerankModelSourceAuto, nil
- }
+ if model := types.PickDefaultModel(models, types.ModelTypeRerank); model != nil {
+ return model.ID, types.RerankModelSourceAuto, nil
}
return "", "", nil
}
diff --git a/internal/application/service/knowledgebase_search_rerank_test.go b/internal/application/service/knowledgebase_search_rerank_test.go
index 33c4c0547..f4daee979 100644
--- a/internal/application/service/knowledgebase_search_rerank_test.go
+++ b/internal/application/service/knowledgebase_search_rerank_test.go
@@ -52,8 +52,8 @@ func newRerankModelService() *rerankModelService {
"chat-1": {ID: "chat-1", Type: types.ModelTypeKnowledgeQA},
},
availableModels: []*types.Model{
- {ID: "chat-1", Type: types.ModelTypeKnowledgeQA},
- {ID: "rr-auto", Type: types.ModelTypeRerank},
+ {ID: "chat-1", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ {ID: "rr-auto", Type: types.ModelTypeRerank, Status: types.ModelStatusActive},
},
}}
}
diff --git a/internal/application/service/knowledgebase_vlm_update_test.go b/internal/application/service/knowledgebase_vlm_update_test.go
index 39fdd0466..bb0f7546b 100644
--- a/internal/application/service/knowledgebase_vlm_update_test.go
+++ b/internal/application/service/knowledgebase_vlm_update_test.go
@@ -32,9 +32,23 @@ func newVLMUpdateService(repo *fakeKBRepo) *knowledgeBaseService {
return &knowledgeBaseService{repo: repo, modelService: &vlmUpdateModelService{models: map[string]*types.Model{
"vlm-1": {ID: "vlm-1", Type: types.ModelTypeVLLM},
"chat-1": {ID: "chat-1", Type: types.ModelTypeKnowledgeQA},
+ "vision-chat": {
+ ID: "vision-chat", Type: types.ModelTypeKnowledgeQA,
+ Parameters: types.ModelParameters{SupportsVision: true},
+ },
}}}
}
+func TestUpdateKnowledgeBaseAcceptsVisionCapableChatModel(t *testing.T) {
+ repo := newFakeKBRepo()
+ repo.rows["kb-1"] = &types.KnowledgeBase{ID: "kb-1", TenantID: 1}
+ kb, err := newVLMUpdateService(repo).UpdateKnowledgeBase(context.Background(), "kb-1", "n", "d", nil,
+ &types.VLMConfig{Enabled: true, ModelID: "vision-chat"})
+ require.NoError(t, err)
+ assert.Equal(t, "vision-chat", kb.VLMConfig.ModelID)
+ assert.True(t, kb.VLMConfig.Enabled)
+}
+
// TestUpdateKnowledgeBaseAppliesVLMConfig guards issue #1723: the KB update
// API previously had no way to change a knowledge base's multimodal (VLM)
// config, because neither the HTTP request nor the service method carried it.
diff --git a/internal/application/service/memory/extract.go b/internal/application/service/memory/extract.go
index df7d2c1eb..9b07c6ab6 100644
--- a/internal/application/service/memory/extract.go
+++ b/internal/application/service/memory/extract.go
@@ -824,12 +824,9 @@ func (s *Service) extractionModelID(
return s.workspaceChatModelID(ctx)
}
-// workspaceChatModelID picks a usable QA model for this workspace.
-//
-// The choice is logged because it is a guess: without an explicitly configured
-// extraction model there is no record of which model the workspace wants used
-// for background work, and silently picking one is only acceptable if it is
-// visible afterwards.
+// workspaceChatModelID prefers the workspace utility model, then the default
+// chat model, then the first active chat model. Log the choice because the
+// queued turn did not specify which model answered it.
func (s *Service) workspaceChatModelID(ctx context.Context) string {
if s.modelService == nil {
return ""
@@ -839,13 +836,7 @@ func (s *Service) workspaceChatModelID(ctx context.Context) string {
logger.Warnf(ctx, "memory: list models for extraction fallback failed: %v", err)
return ""
}
- for _, model := range models {
- if model == nil || model.Type != types.ModelTypeKnowledgeQA {
- continue
- }
- if model.Status != "" && model.Status != types.ModelStatusActive {
- continue
- }
+ if model := types.PickUtilityModel(models); model != nil {
logger.Infof(ctx, "memory: no extraction model configured, using workspace model %s", model.ID)
return model.ID
}
diff --git a/internal/application/service/memory/extract_test.go b/internal/application/service/memory/extract_test.go
index 293230166..5b1da7d2f 100644
--- a/internal/application/service/memory/extract_test.go
+++ b/internal/application/service/memory/extract_test.go
@@ -109,6 +109,22 @@ func TestExtractionPrefersTheConfiguredModel(t *testing.T) {
require.Equal(t, "cheap-model", models.requestedModelID)
}
+func TestExtractionUsesWorkspaceUtilityWithoutRequestContext(t *testing.T) {
+ svc, tenantRepo, messages, models, _ := newExtractionHarness(t)
+ tenantRepo.set(7, &types.MemoryConfig{Enabled: true, WriteMode: types.MemoryWriteAuto})
+ messages.messages = []*types.Message{{ID: "m", Role: "user", Content: "hello"}}
+ models.response = `{"memories":[]}`
+ models.workspaceModels = []*types.Model{
+ {ID: "chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive, IsDefault: true},
+ {ID: "utility", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ }
+ (&types.DefaultSettings{UtilityModelID: "utility"}).ApplyModelDefaults(models.workspaceModels)
+ require.NoError(t, svc.Handle(context.Background(), extractTask(t, types.MemoryExtractPayload{
+ TenantID: 7, SubjectID: "web_user:alice", SessionID: "s", MessageID: "m",
+ })))
+ require.Equal(t, "utility", models.requestedModelID)
+}
+
// TestExtractionReadsOnlyUserMessages is a prompt-injection guard: a document
// or tool result echoed by the assistant must never become a stored fact about
// the user.
diff --git a/internal/application/service/model.go b/internal/application/service/model.go
index 302f49ee9..563c1a782 100644
--- a/internal/application/service/model.go
+++ b/internal/application/service/model.go
@@ -309,11 +309,32 @@ func (s *modelService) ListModels(ctx context.Context) ([]*types.Model, error) {
})
return nil, err
}
+ // GetModelByID is left alone: its result is written back by UpdateModel,
+ // and this overlay must never be persisted.
+ if settings := s.workspaceDefaultSettings(ctx, tenantID); settings != nil {
+ settings.ApplyModelDefaults(models)
+ }
logger.Infof(ctx, "Retrieved %d models successfully", len(models))
return models, nil
}
+// workspaceDefaultSettings prefers the tenant the request already loaded and
+// reads it from storage for background contexts that carry only the ID.
+func (s *modelService) workspaceDefaultSettings(ctx context.Context, tenantID uint64) *types.DefaultSettings {
+ if tenant, ok := types.TenantInfoFromContext(ctx); ok && tenant.ID == tenantID {
+ return tenant.DefaultSettings
+ }
+ if s.tenantService == nil {
+ return nil
+ }
+ tenant, err := s.tenantService.GetTenantByID(ctx, tenantID)
+ if err != nil || tenant == nil {
+ return nil
+ }
+ return tenant.DefaultSettings
+}
+
// UpdateModel updates an existing model in the repository
func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) error {
logger.Info(ctx, "Start updating model")
@@ -756,9 +777,6 @@ func (s *modelService) GetVLMModel(ctx context.Context, modelId string) (vlm.VLM
return vlmModel, nil
}
-// Note: default model selection logic has been removed; models no longer
-// maintain a per-type default flag at the service layer.
-
// GetASRModel retrieves and initializes an automatic speech recognition model instance.
func (s *modelService) GetASRModel(ctx context.Context, modelId string) (asr.ASR, error) {
if modelId == "" {
diff --git a/internal/application/service/model_defaults_test.go b/internal/application/service/model_defaults_test.go
new file mode 100644
index 000000000..63de2dc7d
--- /dev/null
+++ b/internal/application/service/model_defaults_test.go
@@ -0,0 +1,70 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/handler/dto"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type defaultsModelRepository struct {
+ interfaces.ModelRepository
+ models []*types.Model
+}
+
+func (r *defaultsModelRepository) List(
+ context.Context, uint64, types.ModelType, types.ModelSource,
+) ([]*types.Model, error) {
+ models := make([]*types.Model, len(r.models))
+ for i, m := range r.models {
+ cloned := *m
+ models[i] = &cloned
+ }
+ return models, nil
+}
+
+type defaultsTenantService struct {
+ interfaces.TenantService
+ tenant *types.Tenant
+ requestedID uint64
+}
+
+func (s *defaultsTenantService) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
+ s.requestedID = id
+ return s.tenant, nil
+}
+
+func TestListModelsResolvesBackgroundDefaultsByTenantID(t *testing.T) {
+ repo := &defaultsModelRepository{models: []*types.Model{
+ {ID: "chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive, IsDefault: true},
+ {ID: "utility", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ {
+ ID: "vision", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive,
+ Parameters: types.ModelParameters{SupportsVision: true},
+ },
+ }}
+ tenants := &defaultsTenantService{tenant: &types.Tenant{ID: 7, DefaultSettings: &types.DefaultSettings{
+ UtilityModelID: "utility", VLMModelID: "vision",
+ }}}
+ svc := &modelService{repo: repo, tenantService: tenants}
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ // A shared agent may switch tenant ID while retaining the originating tenant info.
+ ctx = context.WithValue(ctx, types.TenantInfoContextKey, &types.Tenant{
+ ID: 99,
+ DefaultSettings: &types.DefaultSettings{UtilityModelID: "chat"},
+ })
+ models, err := svc.ListModels(ctx)
+ require.NoError(t, err)
+ assert.Equal(t, uint64(7), tenants.requestedID)
+ assert.Equal(t, "utility", types.PickUtilityModel(models).ID)
+ assert.Equal(t, "chat", types.PickDefaultModel(models, types.ModelTypeKnowledgeQA).ID)
+ assert.Equal(t, "vision", types.PickDefaultModel(models, types.ModelTypeVLLM).ID)
+ assert.Contains(t, dto.NewModelResponse(ctx, models[2]).DefaultFor, "VLLM")
+ for _, model := range repo.models {
+ assert.Empty(t, model.DefaultFor, "defaults must not be written into stored model rows")
+ }
+}
diff --git a/internal/application/service/session.go b/internal/application/service/session.go
index ca8ac25e5..bb13665c5 100644
--- a/internal/application/service/session.go
+++ b/internal/application/service/session.go
@@ -1041,7 +1041,7 @@ func (s *sessionService) releaseForkSnapshots(ctx context.Context, sessions []*t
}
// GenerateTitle generates a title for the current conversation content
-// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
+// modelID: optional model ID; when empty, uses the workspace utility/chat default.
func (s *sessionService) GenerateTitle(ctx context.Context,
session *types.Session, messages []types.Message, modelID string,
) (string, error) {
@@ -1081,22 +1081,16 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
return "", stderrors.New("no user message found")
}
- // Use provided modelID, or fallback to first available KnowledgeQA model
+ // Use provided modelID, or fall back to the workspace utility/default chat model
if modelID == "" {
models, err := s.modelService.ListModels(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", fmt.Errorf("failed to list models: %w", err)
}
- for _, model := range models {
- if model == nil {
- continue
- }
- if model.Type == types.ModelTypeKnowledgeQA {
- modelID = model.ID
- logger.Infof(ctx, "Using first available KnowledgeQA model for title: %s", modelID)
- break
- }
+ if model := types.PickUtilityModel(models); model != nil {
+ modelID = model.ID
+ logger.Infof(ctx, "Using workspace default KnowledgeQA model for title: %s", modelID)
}
if modelID == "" {
logger.Error(ctx, "No KnowledgeQA model found")
diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go
index 323066a48..00abea16e 100644
--- a/internal/application/service/session_knowledge_qa.go
+++ b/internal/application/service/session_knowledge_qa.go
@@ -319,10 +319,8 @@ func (s *sessionService) selectChatModelID(
if err != nil {
return "", 0, fmt.Errorf("failed to list models: %w", err)
}
- for _, model := range models {
- if model != nil && model.Type == types.ModelTypeKnowledgeQA {
- return model.ID, tenantID, nil
- }
+ if model := types.PickChatModel(models, ""); model != nil {
+ return model.ID, tenantID, nil
}
return "", 0, fmt.Errorf("no chat model ID available: no accessible knowledge base model or available models")
}
diff --git a/internal/application/service/session_model_requirement_test.go b/internal/application/service/session_model_requirement_test.go
index 9ff3e7f54..b633445ff 100644
--- a/internal/application/service/session_model_requirement_test.go
+++ b/internal/application/service/session_model_requirement_test.go
@@ -186,8 +186,9 @@ func TestResolveChatModelIDWikiFixerFallsBackToAvailableModel(t *testing.T) {
modelService: &stubModelService{
availableModels: []*types.Model{
{
- ID: "system-chat",
- Type: types.ModelTypeKnowledgeQA,
+ ID: "system-chat",
+ Type: types.ModelTypeKnowledgeQA,
+ Status: types.ModelStatusActive,
},
},
},
@@ -209,7 +210,9 @@ func TestResolveChatModelIDWikiFixerFallsBackToAvailableModel(t *testing.T) {
func TestResolveChatModelIDFallbackIsLimitedToInternalBuiltins(t *testing.T) {
svc := &sessionService{
modelService: &stubModelService{
- availableModels: []*types.Model{{ID: "system-chat", Type: types.ModelTypeKnowledgeQA}},
+ availableModels: []*types.Model{
+ {ID: "system-chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ },
},
}
assistant := &types.QARequest{
diff --git a/internal/application/service/session_title_generation_test.go b/internal/application/service/session_title_generation_test.go
index 92e74fce6..f9b097926 100644
--- a/internal/application/service/session_title_generation_test.go
+++ b/internal/application/service/session_title_generation_test.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"testing"
+ "time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/models/chat"
@@ -34,12 +35,16 @@ func (*titleGenerationModel) GetModelID() string { return "qa-model" }
type titleGenerationModels struct {
interfaces.ModelService
- model *titleGenerationModel
- selectedID string
+ model *titleGenerationModel
+ selectedID string
+ availableModels []*types.Model
}
-func (*titleGenerationModels) ListModels(context.Context) ([]*types.Model, error) {
- return []*types.Model{{ID: "qa-model", Type: types.ModelTypeKnowledgeQA}}, nil
+func (m *titleGenerationModels) ListModels(context.Context) ([]*types.Model, error) {
+ if m.availableModels != nil {
+ return m.availableModels, nil
+ }
+ return []*types.Model{{ID: "qa-model", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive}}, nil
}
func (m *titleGenerationModels) GetChatModel(_ context.Context, id string) (chat.Chat, error) {
@@ -51,10 +56,14 @@ type titleGenerationRepository struct {
interfaces.SessionRepository
title string
ownerID string
+ done chan struct{}
}
func (r *titleGenerationRepository) Update(_ context.Context, session *types.Session, ownerID string) (int64, error) {
r.title, r.ownerID = session.Title, ownerID
+ if r.done != nil {
+ close(r.done)
+ }
return 1, nil
}
@@ -101,3 +110,33 @@ func TestGenerateTitlePreservesExistingTitle(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "My project", title)
}
+
+func TestGenerateTitleAsyncUsesWorkspaceUtilityDefault(t *testing.T) {
+ for _, explicit := range []string{"", "task-model"} {
+ t.Run("explicit="+explicit, func(t *testing.T) {
+ models := &titleGenerationModels{model: &titleGenerationModel{}, availableModels: []*types.Model{
+ {ID: "chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive, IsDefault: true},
+ {ID: "utility", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ }}
+ (&types.DefaultSettings{UtilityModelID: "utility"}).ApplyModelDefaults(models.availableModels)
+ repo := &titleGenerationRepository{done: make(chan struct{})}
+ svc := &sessionService{
+ cfg: &config.Config{Conversation: &config.ConversationConfig{}},
+ modelService: models,
+ sessionRepo: repo,
+ }
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
+ svc.GenerateTitleAsync(ctx, &types.Session{ID: "session", UserID: "owner"}, "hello", explicit, nil)
+ select {
+ case <-repo.done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("title was not saved")
+ }
+ want := explicit
+ if want == "" {
+ want = "utility"
+ }
+ assert.Equal(t, want, models.selectedID)
+ })
+ }
+}
diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go
index 827db2daa..f7310df69 100644
--- a/internal/application/service/tenant_skill_install.go
+++ b/internal/application/service/tenant_skill_install.go
@@ -2274,17 +2274,8 @@ func (s *TenantSkillService) resolveInstallerModel(
if err != nil {
return nil, fmt.Errorf("list models for installer: %w", err)
}
- for _, model := range models {
- if model != nil && model.Type == types.ModelTypeKnowledgeQA &&
- model.Status == types.ModelStatusActive && model.IsDefault {
- return s.models.GetChatModel(ctx, model.ID)
- }
- }
- for _, model := range models {
- if model != nil && model.Type == types.ModelTypeKnowledgeQA &&
- model.Status == types.ModelStatusActive {
- return s.models.GetChatModel(ctx, model.ID)
- }
+ if model := types.PickChatModel(models, ""); model != nil {
+ return s.models.GetChatModel(ctx, model.ID)
}
return nil, fmt.Errorf("workspace %d has no active chat model for skill installer", tenantID)
}
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index d64fe4250..d8730d8ec 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -88,7 +88,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
-const expectedSQLiteMigrationVersion = 50
+const expectedSQLiteMigrationVersion = 51
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/dto/model.go b/internal/handler/dto/model.go
index 40b21daa7..0a6d3571f 100644
--- a/internal/handler/dto/model.go
+++ b/internal/handler/dto/model.go
@@ -186,6 +186,7 @@ type ModelResponse struct {
Description string `json:"description" extensions:"x-agent"`
Parameters ModelParametersDTO `json:"parameters" extensions:"x-agent"`
IsDefault bool `json:"is_default" extensions:"x-agent"`
+ DefaultFor []string `json:"default_for,omitempty" extensions:"x-agent"`
IsBuiltin bool `json:"is_builtin" extensions:"x-agent"`
Status types.ModelStatus `json:"status" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
@@ -331,6 +332,7 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
Description: m.Description,
Parameters: params,
IsDefault: m.IsDefault,
+ DefaultFor: m.DefaultFor,
IsBuiltin: m.IsBuiltin,
Status: m.Status,
CreatedAt: m.CreatedAt,
diff --git a/internal/handler/mcp_usage_instructions.go b/internal/handler/mcp_usage_instructions.go
index 79bcc6612..64ead92d2 100644
--- a/internal/handler/mcp_usage_instructions.go
+++ b/internal/handler/mcp_usage_instructions.go
@@ -79,18 +79,7 @@ func (h *MCPServiceHandler) GenerateMCPUsageInstructions(c *gin.Context) {
_ = c.Error(errors.NewInternalServerError("Failed to read chat models"))
return
}
- var selected *types.Model
- for _, model := range models {
- if model == nil || model.Type != types.ModelTypeKnowledgeQA || model.Status != types.ModelStatusActive {
- continue
- }
- if selected == nil || model.IsDefault {
- selected = model
- }
- if model.IsDefault {
- break
- }
- }
+ selected := types.PickUtilityModel(models)
if selected == nil {
_ = c.Error(errors.NewBadRequestError("Configure an active chat model before generating usage instructions"))
return
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index 87660c57f..d4a5a4fbe 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -36,6 +36,8 @@ type TenantHandler struct {
// in-code default, so a SystemAdmin's UI override applies on the
// very next CreateTenant call.
systemSettingSvc interfaces.SystemSettingService
+ // modelService validates the models chosen as workspace defaults.
+ modelService interfaces.ModelService
}
// NewTenantHandler creates a new tenant handler instance with the provided service
@@ -63,6 +65,7 @@ func NewTenantHandler(
kbService interfaces.KnowledgeBaseService,
config *config.Config,
systemSettingSvc interfaces.SystemSettingService,
+ modelService interfaces.ModelService,
) *TenantHandler {
return &TenantHandler{
service: service,
@@ -72,6 +75,7 @@ func NewTenantHandler(
kbService: kbService,
config: config,
systemSettingSvc: systemSettingSvc,
+ modelService: modelService,
}
}
@@ -1259,7 +1263,9 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
// GetTenantKV godoc
// @Summary 获取空间KV配置
-// @Description 获取空间级别的KV配置(支持web-search-config、prompt-templates、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
+// @Description 获取空间级别的KV配置。支持 web-search-config、prompt-templates、parser-engine-config、
+// @Description storage-engine-config、chat-history-config、retrieval-config、memory-config、
+// @Description assistant-config、default-settings。
// @Tags 空间管理
// @Accept json
// @Produce json
@@ -1306,6 +1312,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
case "assistant-config":
h.GetTenantAssistantConfig(c)
return
+ case "default-settings":
+ h.GetTenantDefaultSettings(c)
+ return
default:
logger.Info(ctx, "KV key not supported", "key", key)
c.Error(errors.NewBadRequestError("unsupported key"))
@@ -1315,7 +1324,8 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
// UpdateTenantKV godoc
// @Summary 更新空间KV配置
-// @Description 更新空间级别的KV配置(支持web-search-config、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
+// @Description 更新空间级别的KV配置。支持 web-search-config、parser-engine-config、storage-engine-config、
+// @Description chat-history-config、retrieval-config、memory-config、assistant-config、default-settings。
// @Tags 空间管理
// @Accept json
// @Produce json
@@ -1360,6 +1370,9 @@ func (h *TenantHandler) UpdateTenantKV(c *gin.Context) {
case "assistant-config":
h.updateTenantAssistantConfigInternal(c)
return
+ case "default-settings":
+ h.updateTenantDefaultSettingsInternal(c)
+ return
default:
logger.Info(ctx, "KV key not supported", "key", key)
c.Error(errors.NewBadRequestError("unsupported key"))
diff --git a/internal/handler/tenant_default_settings.go b/internal/handler/tenant_default_settings.go
new file mode 100644
index 000000000..a6103cded
--- /dev/null
+++ b/internal/handler/tenant_default_settings.go
@@ -0,0 +1,126 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/gin-gonic/gin"
+)
+
+// GetTenantDefaultSettings returns the workspace's default model choices.
+// Members read it to see which model a feature falls back to; it holds model
+// IDs only, never connection details.
+func (h *TenantHandler) GetTenantDefaultSettings(c *gin.Context) {
+ ctx := c.Request.Context()
+ tenant, _ := types.TenantInfoFromContext(ctx)
+ if tenant == nil {
+ logger.Error(ctx, "Workspace is empty")
+ _ = c.Error(errors.NewBadRequestError("Workspace is empty"))
+ return
+ }
+ data := types.DefaultSettings{}
+ if tenant.DefaultSettings != nil {
+ data = *tenant.DefaultSettings
+ }
+ data.Normalize()
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": data,
+ })
+}
+
+// updateTenantDefaultSettingsInternal replaces the workspace's default model
+// choices. Newly selected IDs must be usable models of the slot's type.
+// Unchanged stale IDs are allowed so admins can repair slots one at a time;
+// an empty ID returns the slot to the deployment default.
+func (h *TenantHandler) updateTenantDefaultSettingsInternal(c *gin.Context) {
+ ctx := c.Request.Context()
+
+ var cfg types.DefaultSettings
+ if err := c.ShouldBindJSON(&cfg); err != nil {
+ logger.Error(ctx, "Failed to parse request parameters", err)
+ _ = c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
+ return
+ }
+ cfg.Normalize()
+
+ tenant, _ := types.TenantInfoFromContext(ctx)
+ if tenant == nil {
+ logger.Error(ctx, "Workspace is empty")
+ _ = c.Error(errors.NewBadRequestError("Workspace is empty"))
+ return
+ }
+ if h.modelService == nil {
+ _ = c.Error(errors.NewServiceUnavailableError("Model service is unavailable"))
+ return
+ }
+ models, err := h.modelService.ListModels(ctx)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, nil)
+ _ = c.Error(errors.NewInternalServerError("Failed to read models"))
+ return
+ }
+ modelsByID := make(map[string]*types.Model, len(models))
+ for _, m := range models {
+ if m != nil {
+ modelsByID[m.ID] = m
+ }
+ }
+ previous := types.DefaultSettings{}
+ if tenant.DefaultSettings != nil {
+ previous = *tenant.DefaultSettings
+ previous.Normalize()
+ }
+ slots := []struct {
+ field string
+ id string
+ previous string
+ want types.ModelType
+ }{
+ {"chat_model_id", cfg.ChatModelID, previous.ChatModelID, types.ModelTypeKnowledgeQA},
+ {"utility_model_id", cfg.UtilityModelID, previous.UtilityModelID, types.ModelTypeKnowledgeQA},
+ {"embedding_model_id", cfg.EmbeddingModelID, previous.EmbeddingModelID, types.ModelTypeEmbedding},
+ {"rerank_model_id", cfg.RerankModelID, previous.RerankModelID, types.ModelTypeRerank},
+ {"vlm_model_id", cfg.VLMModelID, previous.VLMModelID, types.ModelTypeVLLM},
+ {"asr_model_id", cfg.ASRModelID, previous.ASRModelID, types.ModelTypeASR},
+ }
+ for _, slot := range slots {
+ if slot.id == "" || slot.id == slot.previous {
+ continue
+ }
+ model, ok := modelsByID[slot.id]
+ if !ok {
+ _ = c.Error(errors.NewBadRequestError(fmt.Sprintf("%s: model not found", slot.field)))
+ return
+ }
+ if !model.SupportsType(slot.want) {
+ _ = c.Error(errors.NewBadRequestError(fmt.Sprintf("%s must be a %s model", slot.field, slot.want)))
+ return
+ }
+ if model.Status != types.ModelStatusActive {
+ _ = c.Error(errors.NewBadRequestError(fmt.Sprintf("%s: model is not active", slot.field)))
+ return
+ }
+ }
+
+ updated := *tenant
+ updated.DefaultSettings = &cfg
+ updatedTenant, err := h.service.UpdateTenant(ctx, &updated)
+ if err != nil {
+ if appErr, ok := errors.IsAppError(err); ok {
+ _ = c.Error(appErr)
+ } else {
+ logger.ErrorWithFields(ctx, err, nil)
+ _ = c.Error(errors.NewInternalServerError("Failed to update default settings").WithDetails(err.Error()))
+ }
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": updatedTenant.DefaultSettings,
+ "message": "Default settings updated successfully",
+ })
+}
diff --git a/internal/handler/tenant_default_settings_test.go b/internal/handler/tenant_default_settings_test.go
new file mode 100644
index 000000000..78cf4604b
--- /dev/null
+++ b/internal/handler/tenant_default_settings_test.go
@@ -0,0 +1,112 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type defaultSettingsModelsService struct {
+ interfaces.ModelService
+ models []*types.Model
+}
+
+func (s *defaultSettingsModelsService) ListModels(context.Context) ([]*types.Model, error) {
+ return s.models, nil
+}
+
+type defaultSettingsTenantService struct {
+ interfaces.TenantService
+ saved *types.Tenant
+}
+
+func (s *defaultSettingsTenantService) UpdateTenant(_ context.Context, tenant *types.Tenant) (*types.Tenant, error) {
+ s.saved = tenant
+ return tenant, nil
+}
+
+func TestUpdateDefaultSettingsRepairsStaleSlotsIndividually(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ previous, next types.DefaultSettings
+ wantError string
+ }{
+ {
+ name: "clear chat while utility is still stale",
+ previous: types.DefaultSettings{ChatModelID: "deleted", UtilityModelID: "deleted"},
+ next: types.DefaultSettings{UtilityModelID: "deleted"},
+ },
+ {
+ name: "replace chat while utility is still stale",
+ previous: types.DefaultSettings{ChatModelID: "deleted", UtilityModelID: "deleted"},
+ next: types.DefaultSettings{ChatModelID: "chat", UtilityModelID: "deleted"},
+ },
+ {
+ name: "clear remaining stale utility",
+ previous: types.DefaultSettings{ChatModelID: "chat", UtilityModelID: "deleted"},
+ next: types.DefaultSettings{ChatModelID: "chat"},
+ },
+ {
+ name: "new missing selection is rejected",
+ next: types.DefaultSettings{ChatModelID: "deleted"}, wantError: "model not found",
+ },
+ {
+ name: "cannot copy stale ID to a different slot",
+ previous: types.DefaultSettings{ChatModelID: "deleted"},
+ next: types.DefaultSettings{ChatModelID: "deleted", UtilityModelID: "deleted"},
+ wantError: "model not found",
+ },
+ {name: "vision capable chat is accepted", next: types.DefaultSettings{VLMModelID: "vision-chat"}},
+ {
+ name: "text only chat cannot do vision", next: types.DefaultSettings{VLMModelID: "chat"},
+ wantError: "must be a VLLM model",
+ },
+ {
+ name: "inactive models cannot be selected", next: types.DefaultSettings{ChatModelID: "downloading"},
+ wantError: "model is not active",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tenants := &defaultSettingsTenantService{}
+ h := &TenantHandler{service: tenants, modelService: &defaultSettingsModelsService{models: []*types.Model{
+ {ID: "chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive},
+ {
+ ID: "vision-chat", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive,
+ Parameters: types.ModelParameters{SupportsVision: true},
+ },
+ {ID: "downloading", Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusDownloading},
+ }}}
+ body, err := json.Marshal(tc.next)
+ require.NoError(t, err)
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ tenant := &types.Tenant{ID: 7, DefaultSettings: &tc.previous}
+ ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPut, "/tenants/kv/default-settings", bytes.NewReader(body))
+ c.Request = c.Request.WithContext(ctx)
+ c.Request.Header.Set("Content-Type", "application/json")
+ h.updateTenantDefaultSettingsInternal(c)
+ assert.Equal(t, tc.previous, *tenant.DefaultSettings, "do not mutate request tenant")
+ if tc.wantError != "" {
+ require.NotEmpty(t, c.Errors)
+ assert.Contains(t, c.Errors.Last().Error(), tc.wantError)
+ assert.Nil(t, tenants.saved)
+ return
+ }
+ require.Empty(t, c.Errors)
+ assert.Equal(t, http.StatusOK, w.Code)
+ require.NotNil(t, tenants.saved)
+ assert.Equal(t, tc.next, *tenants.saved.DefaultSettings)
+ })
+ }
+}
diff --git a/internal/types/default_settings.go b/internal/types/default_settings.go
new file mode 100644
index 000000000..2ff64ae82
--- /dev/null
+++ b/internal/types/default_settings.go
@@ -0,0 +1,175 @@
+package types
+
+import (
+ "database/sql/driver"
+ "encoding/json"
+ "slices"
+ "strings"
+)
+
+// DefaultSettings is the workspace's choice of default models, stored as
+// JSONB on the tenant. An empty field leaves the slot to the deployment's
+// default (the is_default flag a built-in model YAML sets).
+//
+// The default web search provider is not stored here: providers carry their
+// own is_default flag, which the provider page already edits.
+type DefaultSettings struct {
+ // ChatModelID is the default KnowledgeQA model.
+ ChatModelID string `json:"chat_model_id"`
+ // UtilityModelID is the KnowledgeQA model for short generation tasks
+ // such as writing MCP usage instructions. Empty follows the chat default.
+ UtilityModelID string `json:"utility_model_id"`
+ // EmbeddingModelID is the default Embedding model.
+ EmbeddingModelID string `json:"embedding_model_id"`
+ // RerankModelID is the default Rerank model.
+ RerankModelID string `json:"rerank_model_id"`
+ // VLMModelID is the default VLLM or vision-capable KnowledgeQA model.
+ VLMModelID string `json:"vlm_model_id"`
+ // ASRModelID is the default ASR model.
+ ASRModelID string `json:"asr_model_id"`
+}
+
+// Normalize trims every ID.
+func (c *DefaultSettings) Normalize() {
+ c.ChatModelID = strings.TrimSpace(c.ChatModelID)
+ c.UtilityModelID = strings.TrimSpace(c.UtilityModelID)
+ c.EmbeddingModelID = strings.TrimSpace(c.EmbeddingModelID)
+ c.RerankModelID = strings.TrimSpace(c.RerankModelID)
+ c.VLMModelID = strings.TrimSpace(c.VLMModelID)
+ c.ASRModelID = strings.TrimSpace(c.ASRModelID)
+}
+
+// ModelSlots maps each model-type slot to the capability its model must support. The
+// utility slot is a KnowledgeQA model chosen for a purpose rather than a
+// type, so it is listed separately by callers that validate it.
+func (c *DefaultSettings) ModelSlots() map[ModelType]string {
+ if c == nil {
+ return nil
+ }
+ return map[ModelType]string{
+ ModelTypeKnowledgeQA: c.ChatModelID,
+ ModelTypeEmbedding: c.EmbeddingModelID,
+ ModelTypeRerank: c.RerankModelID,
+ ModelTypeVLLM: c.VLMModelID,
+ ModelTypeASR: c.ASRModelID,
+ }
+}
+
+// ApplyModelDefaults projects workspace defaults onto a fresh model list.
+// IsDefault remains specific to the model's native type. DefaultFor also
+// represents cross-type vision choices and the utility purpose. Missing or
+// inactive choices leave deployment defaults in effect.
+func (c *DefaultSettings) ApplyModelDefaults(models []*Model) {
+ for modelType, id := range c.ModelSlots() {
+ if id == "" || !hasActiveModel(models, id, modelType) {
+ continue
+ }
+ for _, m := range models {
+ if m == nil {
+ continue
+ }
+ if m.ID == id {
+ m.DefaultFor = append(m.DefaultFor, string(modelType))
+ }
+ if m.Type == modelType {
+ m.IsDefault = m.ID == id
+ }
+ }
+ }
+ if c != nil && hasActiveModel(models, c.UtilityModelID, ModelTypeKnowledgeQA) {
+ for _, m := range models {
+ if m != nil && m.ID == c.UtilityModelID {
+ m.DefaultFor = append(m.DefaultFor, "Utility")
+ }
+ }
+ }
+}
+
+// SupportsType includes chat models that can also be used for vision.
+func (m *Model) SupportsType(modelType ModelType) bool {
+ return m.Type == modelType || (modelType == ModelTypeVLLM &&
+ m.Type == ModelTypeKnowledgeQA && m.Parameters.SupportsVision)
+}
+
+// PickUtilityModel resolves background defaults from ListModels, including
+// workers whose context carries only a tenant ID. An explicit task model is
+// handled by the caller before falling back here.
+func PickUtilityModel(models []*Model) *Model {
+ for _, m := range models {
+ if m != nil && m.Type == ModelTypeKnowledgeQA && m.Status == ModelStatusActive &&
+ slices.Contains(m.DefaultFor, "Utility") {
+ return m
+ }
+ }
+ return PickDefaultModel(models, ModelTypeKnowledgeQA)
+}
+
+// PickDefaultModel prefers a workspace purpose default, then a deployment
+// default of the native type, then the first usable model.
+func PickDefaultModel(models []*Model, modelType ModelType) *Model {
+ var first, deploymentDefault *Model
+ for _, m := range models {
+ if m == nil || !m.SupportsType(modelType) || m.Status != ModelStatusActive {
+ continue
+ }
+ if slices.Contains(m.DefaultFor, string(modelType)) {
+ return m
+ }
+ if deploymentDefault == nil && m.Type == modelType && m.IsDefault {
+ deploymentDefault = m
+ }
+ if first == nil {
+ first = m
+ }
+ }
+ if deploymentDefault != nil {
+ return deploymentDefault
+ }
+ return first
+}
+
+// PickChatModel returns the active KnowledgeQA model to use for a background
+// task: preferredID when it is usable, else the default, else the first
+// active one. Nil means the workspace has no active chat model.
+func PickChatModel(models []*Model, preferredID string) *Model {
+ if preferredID != "" && hasActiveModel(models, preferredID, ModelTypeKnowledgeQA) {
+ for _, m := range models {
+ if m != nil && m.ID == preferredID {
+ return m
+ }
+ }
+ }
+ return PickDefaultModel(models, ModelTypeKnowledgeQA)
+}
+
+func hasActiveModel(models []*Model, id string, modelType ModelType) bool {
+ for _, m := range models {
+ if m != nil && m.ID == id && m.SupportsType(modelType) && m.Status == ModelStatusActive {
+ return true
+ }
+ }
+ return false
+}
+
+// Value implements driver.Valuer for JSON storage.
+func (c DefaultSettings) Value() (driver.Value, error) { return json.Marshal(c) }
+
+// Scan implements sql.Scanner for JSON storage.
+func (c *DefaultSettings) Scan(value interface{}) error {
+ if value == nil {
+ return nil
+ }
+ var b []byte
+ switch v := value.(type) {
+ case []byte:
+ b = v
+ case string:
+ b = []byte(v)
+ default:
+ return nil
+ }
+ if len(b) == 0 {
+ return nil
+ }
+ return json.Unmarshal(b, c)
+}
diff --git a/internal/types/default_settings_test.go b/internal/types/default_settings_test.go
new file mode 100644
index 000000000..2dc65a4f5
--- /dev/null
+++ b/internal/types/default_settings_test.go
@@ -0,0 +1,120 @@
+package types
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func defaultSettingsModels() []*Model {
+ return []*Model{
+ {ID: "chat-a", Type: ModelTypeKnowledgeQA, Status: ModelStatusActive},
+ {ID: "chat-yaml", Type: ModelTypeKnowledgeQA, Status: ModelStatusActive, IsDefault: true},
+ {ID: "chat-down", Type: ModelTypeKnowledgeQA, Status: ModelStatusDownloading},
+ {ID: "rerank-a", Type: ModelTypeRerank, Status: ModelStatusActive},
+ }
+}
+
+func TestApplyModelDefaultsOverridesDeploymentDefault(t *testing.T) {
+ models := defaultSettingsModels()
+ (&DefaultSettings{ChatModelID: "chat-a", RerankModelID: "rerank-a"}).ApplyModelDefaults(models)
+
+ assert.True(t, models[0].IsDefault)
+ assert.False(t, models[1].IsDefault, "the workspace choice replaces the YAML default")
+ assert.True(t, models[3].IsDefault)
+}
+
+func TestApplyModelDefaultsIgnoresUnusableChoice(t *testing.T) {
+ for name, id := range map[string]string{
+ "missing": "gone",
+ "inactive": "chat-down",
+ "wrong type": "rerank-a",
+ "empty choice": "",
+ } {
+ t.Run(name, func(t *testing.T) {
+ models := defaultSettingsModels()
+ (&DefaultSettings{ChatModelID: id}).ApplyModelDefaults(models)
+ assert.True(t, models[1].IsDefault, "the deployment default must still apply")
+ assert.False(t, models[0].IsDefault)
+ })
+ }
+}
+
+func TestApplyModelDefaultsNilSettings(t *testing.T) {
+ models := defaultSettingsModels()
+ var settings *DefaultSettings
+ settings.ApplyModelDefaults(models)
+ assert.True(t, models[1].IsDefault)
+}
+
+func TestPickChatModel(t *testing.T) {
+ models := defaultSettingsModels()
+ assert.Equal(t, "chat-a", PickChatModel(models, "chat-a").ID)
+ assert.Equal(t, "chat-yaml", PickChatModel(models, "").ID)
+ assert.Equal(t, "chat-yaml", PickChatModel(models, "chat-down").ID, "an inactive preference falls back")
+ assert.Equal(t, "chat-yaml", PickChatModel(models, "rerank-a").ID, "a non-chat preference falls back")
+
+ models[1].IsDefault = false
+ assert.Equal(t, "chat-a", PickChatModel(models, "").ID, "without a default the first active model is used")
+ assert.Nil(t, PickChatModel(models[3:], ""))
+}
+
+func TestPickDefaultModelSkipsInactive(t *testing.T) {
+ models := []*Model{
+ {ID: "r1", Type: ModelTypeRerank, Status: ModelStatusDownloading, IsDefault: true},
+ {ID: "r2", Type: ModelTypeRerank, Status: ModelStatusActive},
+ }
+ assert.Equal(t, "r2", PickDefaultModel(models, ModelTypeRerank).ID)
+ assert.Nil(t, PickDefaultModel(models, ModelTypeEmbedding))
+}
+
+func TestPickUtilityModel(t *testing.T) {
+ for _, id := range []string{"chat-a", "gone", "chat-down", "rerank-a", ""} {
+ t.Run(id, func(t *testing.T) {
+ models := defaultSettingsModels()
+ (&DefaultSettings{UtilityModelID: id}).ApplyModelDefaults(models)
+ want := "chat-yaml"
+ if id == "chat-a" {
+ want = id
+ }
+ assert.Equal(t, want, PickUtilityModel(models).ID)
+ assert.Equal(t, "chat-yaml", PickChatModel(models, "").ID)
+ })
+ }
+ assert.Nil(t, PickUtilityModel(nil))
+}
+
+func TestVisionDefaultDoesNotReplaceChatDefault(t *testing.T) {
+ models := []*Model{
+ {
+ ID: "chat", Type: ModelTypeKnowledgeQA, Status: ModelStatusActive,
+ Parameters: ModelParameters{SupportsVision: true},
+ },
+ {
+ ID: "vision-chat", Type: ModelTypeKnowledgeQA, Status: ModelStatusActive,
+ Parameters: ModelParameters{SupportsVision: true},
+ },
+ {ID: "vision-yaml", Type: ModelTypeVLLM, Status: ModelStatusActive, IsDefault: true},
+ {ID: "asr", Type: ModelTypeASR, Status: ModelStatusActive},
+ }
+ (&DefaultSettings{ChatModelID: "chat", VLMModelID: "vision-chat", ASRModelID: "asr"}).ApplyModelDefaults(models)
+ assert.Equal(t, "chat", PickDefaultModel(models, ModelTypeKnowledgeQA).ID)
+ assert.Equal(t, "vision-chat", PickDefaultModel(models, ModelTypeVLLM).ID)
+ assert.Equal(t, "asr", PickDefaultModel(models, ModelTypeASR).ID)
+ assert.True(t, models[0].IsDefault)
+ assert.False(t, models[1].IsDefault)
+ assert.False(t, models[2].IsDefault)
+ assert.Contains(t, models[1].DefaultFor, string(ModelTypeVLLM))
+}
+
+func TestVisionFallbackPrefersNativeDefaultOverChatDefault(t *testing.T) {
+ models := []*Model{
+ {
+ ID: "chat", Type: ModelTypeKnowledgeQA, Status: ModelStatusActive, IsDefault: true,
+ Parameters: ModelParameters{SupportsVision: true},
+ },
+ {ID: "vision", Type: ModelTypeVLLM, Status: ModelStatusActive, IsDefault: true},
+ }
+ (&DefaultSettings{VLMModelID: "deleted"}).ApplyModelDefaults(models)
+ assert.Equal(t, "vision", PickDefaultModel(models, ModelTypeVLLM).ID)
+}
diff --git a/internal/types/model.go b/internal/types/model.go
index 633cbf285..c5af9781a 100644
--- a/internal/types/model.go
+++ b/internal/types/model.go
@@ -233,6 +233,10 @@ type Model struct {
Parameters ModelParameters `yaml:"parameters" json:"parameters" gorm:"type:json"`
// Whether the model is the default model
IsDefault bool `yaml:"is_default" json:"is_default"`
+ // DefaultFor lists workspace default purposes (model types or "Utility").
+ // It is projected by ListModels, never stored; a vision-capable chat model
+ // can be the vision default independently of the chat default.
+ DefaultFor []string `yaml:"-" json:"default_for,omitempty" gorm:"-"`
// Whether the model is a builtin model (visible to all tenants)
IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`
// ManagedBy identifies which subsystem owns this row's lifecycle.
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index 4512800e5..abfbdcdb8 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -120,6 +120,8 @@ type Tenant struct {
MemoryConfig *MemoryConfig `yaml:"memory_config" json:"memory_config" gorm:"type:jsonb"`
// Assistant config: display name and access ceiling of the WeKnora assistant
AssistantConfig *AssistantConfig `yaml:"assistant_config" json:"assistant_config" gorm:"type:jsonb"`
+ // Default settings: the workspace's default model for each type and purpose
+ DefaultSettings *DefaultSettings `yaml:"default_settings" json:"default_settings" gorm:"type:jsonb"`
// API principal config: controls how X-API-Key requests map to terminal principals.
APIPrincipalConfig *APIPrincipalConfig `yaml:"api_principal_config" json:"-" gorm:"type:jsonb"`
// Creation time
diff --git a/migrations/sqlite/000051_tenant_default_settings.down.sql b/migrations/sqlite/000051_tenant_default_settings.down.sql
new file mode 100644
index 000000000..1be16de02
--- /dev/null
+++ b/migrations/sqlite/000051_tenant_default_settings.down.sql
@@ -0,0 +1 @@
+ALTER TABLE tenants DROP COLUMN default_settings;
diff --git a/migrations/sqlite/000051_tenant_default_settings.up.sql b/migrations/sqlite/000051_tenant_default_settings.up.sql
new file mode 100644
index 000000000..0b12fd184
--- /dev/null
+++ b/migrations/sqlite/000051_tenant_default_settings.up.sql
@@ -0,0 +1 @@
+ALTER TABLE tenants ADD COLUMN default_settings TEXT;
diff --git a/migrations/versioned/000134_tenant_default_settings.down.sql b/migrations/versioned/000134_tenant_default_settings.down.sql
new file mode 100644
index 000000000..8aca409ed
--- /dev/null
+++ b/migrations/versioned/000134_tenant_default_settings.down.sql
@@ -0,0 +1 @@
+ALTER TABLE tenants DROP COLUMN IF EXISTS default_settings;
diff --git a/migrations/versioned/000134_tenant_default_settings.up.sql b/migrations/versioned/000134_tenant_default_settings.up.sql
new file mode 100644
index 000000000..3c2e6bb0b
--- /dev/null
+++ b/migrations/versioned/000134_tenant_default_settings.up.sql
@@ -0,0 +1,5 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000134] Adding tenants.default_settings...'; END $$;
+
+-- Workspace default model for each type and purpose. Empty slots fall back
+-- to the is_default flag on model rows.
+ALTER TABLE tenants ADD COLUMN IF NOT EXISTS default_settings JSONB;
diff --git a/website-docs/04-api/02-api-tenant.md b/website-docs/04-api/02-api-tenant.md
index ce344acf5..c1a5db7a6 100644
--- a/website-docs/04-api/02-api-tenant.md
+++ b/website-docs/04-api/02-api-tenant.md
@@ -100,10 +100,12 @@ curl -X DELETE $BASE/api/v1/tenants/1 -H "Authorization: Bearer $TOKEN"
## 空间 KV 配置
-`:key` 为配置键而非空间 ID(空间取自认证上下文),可选值:`web-search-config`、`prompt-templates`、`parser-engine-config`、`storage-engine-config`、`chat-history-config`、`retrieval-config`、`memory-config`、`assistant-config`。
+`:key` 为配置键而非空间 ID(空间取自认证上下文),可选值:`web-search-config`、`prompt-templates`、`parser-engine-config`、`storage-engine-config`、`chat-history-config`、`retrieval-config`、`memory-config`、`assistant-config`、`default-settings`。
`assistant-config` 是 WeKnora 助手的空间设置:`display_name`(界面上的助手名称,最多 24 字,空表示默认名称)和 `max_access_level`(成员可选的最高权限等级:`read_only` 只读、`confirm` 修改前确认、`auto_write` 可恢复的修改直接执行,删除类仍需确认;默认 `confirm`)。成员在对话请求里用 `assistant_access` 选择自己的等级,服务端按空间上限截断。
+`default-settings` 是空间默认模型:`chat_model_id`、`utility_model_id`(标题、MCP 使用说明、记忆提取等短文本生成,空表示跟随 `chat_model_id`)、`embedding_model_id`、`rerank_model_id`、`vlm_model_id`、`asr_model_id`。读取需 Viewer+,写入需 Admin+;PUT 提交完整对象,非空 ID 必须是本空间可用且类型匹配的模型,空字符串表示使用部署内置模型的 `is_default`。智能体、知识库等资源上显式选择的模型优先于空间默认;所选模型被删除或停用时自动回退到部署默认,再回退到第一个可用模型。设置生效后,`GET /models` 返回的 `is_default` 表示每种类型当前生效的默认模型。默认搜索引擎仍由网络搜索服务的 `is_default` 决定(`PATCH /web-search-providers/:id`)。
+
### GET /api/v1/tenants/kv/:key
用途:读取空间级 KV 配置。权限:Viewer+;API key 需 `manage_tenant_settings` 或 full-access。Handler: `internal/handler/tenant.go`