feat(assistant): let the assistant manage knowledge bases (#4353)
* feat(assistant): let the assistant manage knowledge bases Create, update, and delete knowledge bases, tags, and manual Markdown, and show those confirmations as labeled rows with model names. * fix(assistant): satisfy lint on knowledge base operations Check new error returns, wrap lines past 120 characters, and document the exported tag request types. * fix(assistant): enforce knowledge base settings permissions and preserve patch fieldsmain
parent
aeeb72a61a
commit
2fbfb44715
|
|
@ -858,9 +858,15 @@ type UpdateManualKnowledgeRequest struct {
|
|||
Content string `json:"content,omitempty"`
|
||||
}
|
||||
|
||||
// BatchUpdateKnowledgeTagsRequest contains the mapping of knowledge IDs to tag IDs.
|
||||
// BatchUpdateKnowledgeTagsRequest sets tags on documents.
|
||||
// Send Updates, or KnowledgeIDs together with TagIDs. An empty TagIDs clears
|
||||
// the tags; omitting it while KnowledgeIDs is set is rejected.
|
||||
type BatchUpdateKnowledgeTagsRequest struct {
|
||||
Updates map[string]*string `json:"updates"` // knowledge_id -> tag_id (nil to clear)
|
||||
Updates map[string]*string `json:"updates,omitempty"` // knowledge_id -> tag_id (nil to clear)
|
||||
KBID string `json:"kb_id,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
// Keep an explicit empty array on the wire; nil remains null and is rejected in the list form.
|
||||
TagIDs []string `json:"tag_ids"`
|
||||
}
|
||||
|
||||
// CreateManualKnowledge creates a knowledge entry from manual Markdown content.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBatchKnowledgeTagsPreservesEmptyList(t *testing.T) {
|
||||
for _, tags := range [][]string{nil, {}, {"tag-1"}} {
|
||||
request := BatchUpdateKnowledgeTagsRequest{KnowledgeIDs: []string{"k-1"}, TagIDs: tags}
|
||||
body, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Decode as the server does: nil is rejected, [] deliberately clears tags.
|
||||
var received struct {
|
||||
KnowledgeIDs []string `json:"knowledge_ids"`
|
||||
TagIDs []string `json:"tag_ids"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &received); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(tags, received.TagIDs) {
|
||||
t.Errorf("tags = %#v, want %#v; body = %s", received.TagIDs, tags, body)
|
||||
}
|
||||
if !reflect.DeepEqual(request.KnowledgeIDs, received.KnowledgeIDs) {
|
||||
t.Errorf("knowledge IDs = %#v, want %#v", received.KnowledgeIDs, request.KnowledgeIDs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,6 +56,14 @@ type ChunkingConfig struct {
|
|||
Separators []string `json:"separators"` // Separators
|
||||
}
|
||||
|
||||
// IndexingStrategy selects which indexing pipelines are active.
|
||||
type IndexingStrategy struct {
|
||||
VectorEnabled bool `json:"vector_enabled"`
|
||||
KeywordEnabled bool `json:"keyword_enabled"`
|
||||
WikiEnabled bool `json:"wiki_enabled"`
|
||||
GraphEnabled bool `json:"graph_enabled"`
|
||||
}
|
||||
|
||||
// FAQConfig represents faq-specific configuration
|
||||
type FAQConfig struct {
|
||||
IndexMode string `json:"index_mode"`
|
||||
|
|
@ -356,6 +364,90 @@ func (c *Client) UpdateKnowledgeBase(ctx context.Context,
|
|||
return &response.Data, nil
|
||||
}
|
||||
|
||||
// PatchKnowledgeBaseRequest changes only the fields it carries.
|
||||
// A nil field is left unchanged. Nested objects use pointers so a false or
|
||||
// zero value can be sent without the other fields being cleared.
|
||||
type PatchKnowledgeBaseRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
EmbeddingModelID *string `json:"embedding_model_id,omitempty"`
|
||||
SummaryModelID *string `json:"summary_model_id,omitempty"`
|
||||
StorageBackendID *string `json:"storage_backend_id,omitempty"`
|
||||
ChunkingConfig *PatchChunkingConfig `json:"chunking_config,omitempty"`
|
||||
IndexingStrategy *PatchIndexingStrategy `json:"indexing_strategy,omitempty"`
|
||||
VLMConfig *PatchVLMConfig `json:"vlm_config,omitempty"`
|
||||
ASRConfig *PatchASRConfig `json:"asr_config,omitempty"`
|
||||
FAQConfig *PatchFAQConfig `json:"faq_config,omitempty"`
|
||||
AutoTagConfig *PatchAutoTagConfig `json:"auto_tag_config,omitempty"`
|
||||
ImageProcessing *PatchImageProcessingConfig `json:"image_processing_config,omitempty"`
|
||||
}
|
||||
|
||||
// PatchChunkingConfig is the partial chunking update. Nil fields stay as they are.
|
||||
type PatchChunkingConfig struct {
|
||||
ChunkSize *int `json:"chunk_size,omitempty"`
|
||||
ChunkOverlap *int `json:"chunk_overlap,omitempty"`
|
||||
Separators *[]string `json:"separators,omitempty"`
|
||||
}
|
||||
|
||||
// PatchIndexingStrategy is the partial indexing update. Nil flags stay as they are.
|
||||
type PatchIndexingStrategy struct {
|
||||
VectorEnabled *bool `json:"vector_enabled,omitempty"`
|
||||
KeywordEnabled *bool `json:"keyword_enabled,omitempty"`
|
||||
WikiEnabled *bool `json:"wiki_enabled,omitempty"`
|
||||
GraphEnabled *bool `json:"graph_enabled,omitempty"`
|
||||
}
|
||||
|
||||
// PatchVLMConfig is the partial caption-model update.
|
||||
type PatchVLMConfig struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
ModelID *string `json:"model_id,omitempty"`
|
||||
}
|
||||
|
||||
// PatchASRConfig changes only the speech-recognition fields provided.
|
||||
type PatchASRConfig struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
ModelID *string `json:"model_id,omitempty"`
|
||||
Language *string `json:"language,omitempty"`
|
||||
}
|
||||
|
||||
// PatchFAQConfig changes only the FAQ indexing fields provided.
|
||||
type PatchFAQConfig struct {
|
||||
IndexMode *string `json:"index_mode,omitempty"`
|
||||
QuestionIndexMode *string `json:"question_index_mode,omitempty"`
|
||||
}
|
||||
|
||||
// PatchAutoTagConfig changes only the automatic tagging fields provided.
|
||||
type PatchAutoTagConfig struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
ModelID *string `json:"model_id,omitempty"`
|
||||
MaxTags *int `json:"max_tags,omitempty"`
|
||||
SkipIfTagged *bool `json:"skip_if_tagged,omitempty"`
|
||||
}
|
||||
|
||||
// PatchImageProcessingConfig changes only the image settings provided.
|
||||
type PatchImageProcessingConfig struct {
|
||||
ModelID *string `json:"model_id,omitempty"`
|
||||
}
|
||||
|
||||
// PatchKnowledgeBase changes the supplied settings and preserves omitted fields.
|
||||
func (c *Client) PatchKnowledgeBase(ctx context.Context,
|
||||
knowledgeBaseID string,
|
||||
request *PatchKnowledgeBaseRequest,
|
||||
) (*KnowledgeBase, error) {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s", knowledgeBaseID)
|
||||
resp, err := c.doRequest(ctx, http.MethodPatch, path, request, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var response KnowledgeBaseResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &response.Data, nil
|
||||
}
|
||||
|
||||
// DeleteKnowledgeBase deletes a knowledge base
|
||||
func (c *Client) DeleteKnowledgeBase(ctx context.Context, knowledgeBaseID string) error {
|
||||
path := fmt.Sprintf("/api/v1/knowledge-bases/%s", knowledgeBaseID)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPatchKnowledgeBasePreservesFieldPresence(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{}`,
|
||||
`{"asr_config":{"language":"en"}}`,
|
||||
`{"asr_config":{"enabled":false}}`,
|
||||
`{"asr_config":{"model_id":""}}`,
|
||||
`{"asr_config":{"language":""}}`,
|
||||
`{"faq_config":{"question_index_mode":"separate"}}`,
|
||||
`{"faq_config":{"index_mode":"question_only"}}`,
|
||||
`{"auto_tag_config":{"max_tags":5}}`,
|
||||
`{"auto_tag_config":{"enabled":false,"skip_if_tagged":false}}`,
|
||||
`{"auto_tag_config":{"model_id":"","max_tags":0}}`,
|
||||
`{"image_processing_config":{}}`,
|
||||
`{"image_processing_config":{"model_id":""}}`,
|
||||
`{"chunking_config":{"chunk_overlap":0,"separators":[]}}`,
|
||||
`{"indexing_strategy":{"vector_enabled":false}}`,
|
||||
`{"vlm_config":{"enabled":false}}`,
|
||||
} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
var request PatchKnowledgeBaseRequest
|
||||
if err := json.Unmarshal([]byte(body), &request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var want map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPatch || r.URL.Path != "/api/v1/knowledge-bases/kb-1" {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !reflect.DeepEqual(want, got) {
|
||||
t.Errorf("request changed field presence: got %#v, want %#v", got, want)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(map[string]any{
|
||||
"success": true, "data": map[string]any{"id": "kb-1"},
|
||||
}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
kb, err := NewClient(srv.URL).PatchKnowledgeBase(context.Background(), "kb-1", &request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kb.ID != "kb-1" {
|
||||
t.Errorf("unexpected knowledge base: %#v", kb)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -162,6 +162,11 @@ templates:
|
|||
- List skills with skill.list using the agent's sandbox_config_id (host when it has none) and use their names exactly. If none are listed or the agent is not in smart-reasoning mode, explain what the user needs to change in the agent editor instead of guessing.
|
||||
- Built-in agents are shared by the whole workspace; before changing one, confirm with ask_user that the user means to change it for everyone.
|
||||
- Model endpoints and keys, MCP connection settings and credentials, and sharing or publishing an agent are outside what you can do. Tell the user where in WeKnora to do it.
|
||||
Looking after knowledge bases:
|
||||
- Create one with knowledge_base.create. Omit type for a document knowledge base. Omit the indexing flags for vector and keyword search. Model ids come from model.list. vector_store_id can be chosen only at creation.
|
||||
- knowledge_base.update changes the settings you send. A field left out is kept, including one indexing flag or one chunk size. embedding_model_id cannot change after the knowledge base has documents. vector_store_id cannot be changed. Graph node and relation types stay in the knowledge base editor.
|
||||
- Tags belong to a knowledge base. Create or rename them there, then set them on documents with knowledge.set_tags. Deleting a tag fails while documents still use it; take it off those documents first. Do not delete documents to remove a tag.
|
||||
- knowledge.update_manual replaces the whole Markdown of a document that was created as manual knowledge. Send the complete text. Uploaded files are not edited this way.
|
||||
Questions about WeKnora itself:
|
||||
- For how a feature works, how to configure or deploy it, environment variables, the API or what changed in a release, search the documentation with search_weknora_docs and read the relevant section with read_weknora_doc before answering. It is the documentation of the version the user is running.
|
||||
- The documentation explains how WeKnora works; operations show how this workspace actually is. When the two seem to disagree, trust the operation result and say so.
|
||||
|
|
|
|||
845
docs/docs.go
845
docs/docs.go
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -6396,7 +6396,47 @@ export default {
|
|||
invalidJson: 'Arguments must be valid JSON',
|
||||
submitted: 'Submitted',
|
||||
submitFailed: 'Submit failed',
|
||||
userRejected: 'User rejected'
|
||||
userRejected: 'User rejected',
|
||||
detail: {
|
||||
type: 'Type',
|
||||
embeddingModel: 'Embedding model',
|
||||
summaryModel: 'Summary model',
|
||||
captionModel: 'Caption model',
|
||||
speechModel: 'Speech model',
|
||||
storage: 'Storage',
|
||||
indexes: 'Indexes',
|
||||
name: 'Name',
|
||||
title: 'Title',
|
||||
status: 'Status',
|
||||
summary: 'Summary',
|
||||
model: 'Model',
|
||||
mode: 'Mode',
|
||||
url: 'URL',
|
||||
from: 'From',
|
||||
to: 'To',
|
||||
folder: 'Folder',
|
||||
page: 'Page',
|
||||
version: 'Version',
|
||||
documents: 'Documents',
|
||||
knowledgeBases: 'Knowledge bases',
|
||||
mcpServices: 'MCP services',
|
||||
skills: 'Skills',
|
||||
webSearch: 'Web search',
|
||||
multiTurn: 'Multi-turn conversation'
|
||||
},
|
||||
value: {
|
||||
document: 'Document',
|
||||
faq: 'FAQ',
|
||||
wiki: 'Wiki',
|
||||
on: 'On',
|
||||
off: 'Off',
|
||||
vector: 'Vector',
|
||||
keyword: 'Keyword',
|
||||
graph: 'Graph',
|
||||
quickAnswer: 'Quick answer',
|
||||
smartReasoning: 'Smart reasoning',
|
||||
indexSep: ', '
|
||||
}
|
||||
},
|
||||
mcpOAuth: {
|
||||
waiting: 'Awaiting authorization · {target}',
|
||||
|
|
|
|||
|
|
@ -6396,7 +6396,47 @@ export default {
|
|||
invalidJson: '引数は有効なJSONである必要があります',
|
||||
submitted: '送信しました',
|
||||
submitFailed: '送信に失敗しました',
|
||||
userRejected: 'ユーザが拒否しました'
|
||||
userRejected: 'ユーザが拒否しました',
|
||||
detail: {
|
||||
type: '種類',
|
||||
embeddingModel: '埋め込みモデル',
|
||||
summaryModel: '要約モデル',
|
||||
captionModel: '画像説明',
|
||||
speechModel: '音声認識',
|
||||
storage: 'ストレージ',
|
||||
indexes: 'インデックス',
|
||||
name: '名前',
|
||||
title: 'タイトル',
|
||||
status: '状態',
|
||||
summary: '説明',
|
||||
model: 'モデル',
|
||||
mode: 'モード',
|
||||
url: 'リンク',
|
||||
from: '移動元',
|
||||
to: '移動先',
|
||||
folder: 'フォルダ',
|
||||
page: 'ページ',
|
||||
version: 'バージョン',
|
||||
documents: 'ドキュメント',
|
||||
knowledgeBases: 'ナレッジベース',
|
||||
mcpServices: 'MCP サービス',
|
||||
skills: 'スキル',
|
||||
webSearch: 'ウェブ検索',
|
||||
multiTurn: 'マルチターン'
|
||||
},
|
||||
value: {
|
||||
document: 'ドキュメント',
|
||||
faq: 'FAQ',
|
||||
wiki: 'Wiki',
|
||||
on: 'オン',
|
||||
off: 'オフ',
|
||||
vector: 'ベクトル',
|
||||
keyword: 'キーワード',
|
||||
graph: 'グラフ',
|
||||
quickAnswer: 'クイック回答',
|
||||
smartReasoning: 'スマート推論',
|
||||
indexSep: '、'
|
||||
}
|
||||
},
|
||||
mcpOAuth: {
|
||||
waiting: '認可待ち · {target}',
|
||||
|
|
|
|||
|
|
@ -1967,7 +1967,47 @@ export default {
|
|||
invalidJson: '유효한 JSON이 아닙니다',
|
||||
submitted: '제출됨',
|
||||
submitFailed: '제출 실패',
|
||||
userRejected: '사용자 거부'
|
||||
userRejected: '사용자 거부',
|
||||
detail: {
|
||||
type: '유형',
|
||||
embeddingModel: '임베딩 모델',
|
||||
summaryModel: '요약 모델',
|
||||
captionModel: '이미지 설명',
|
||||
speechModel: '음성 인식',
|
||||
storage: '스토리지',
|
||||
indexes: '인덱스',
|
||||
name: '이름',
|
||||
title: '제목',
|
||||
status: '상태',
|
||||
summary: '설명',
|
||||
model: '모델',
|
||||
mode: '모드',
|
||||
url: '링크',
|
||||
from: '출발',
|
||||
to: '도착',
|
||||
folder: '폴더',
|
||||
page: '페이지',
|
||||
version: '버전',
|
||||
documents: '문서',
|
||||
knowledgeBases: '지식베이스',
|
||||
mcpServices: 'MCP 서비스',
|
||||
skills: '스킬',
|
||||
webSearch: '웹 검색',
|
||||
multiTurn: '멀티턴'
|
||||
},
|
||||
value: {
|
||||
document: '문서',
|
||||
faq: 'FAQ',
|
||||
wiki: 'Wiki',
|
||||
on: '켜짐',
|
||||
off: '꺼짐',
|
||||
vector: '벡터',
|
||||
keyword: '키워드',
|
||||
graph: '그래프',
|
||||
quickAnswer: '빠른 답변',
|
||||
smartReasoning: '스마트 추론',
|
||||
indexSep: ', '
|
||||
}
|
||||
}
|
||||
},
|
||||
kbSettings: {
|
||||
|
|
|
|||
|
|
@ -1967,7 +1967,47 @@ export default {
|
|||
invalidJson: 'Некорректный JSON',
|
||||
submitted: 'Отправлено',
|
||||
submitFailed: 'Ошибка отправки',
|
||||
userRejected: 'Отклонено пользователем'
|
||||
userRejected: 'Отклонено пользователем',
|
||||
detail: {
|
||||
type: 'Тип',
|
||||
embeddingModel: 'Модель эмбеддинга',
|
||||
summaryModel: 'Модель сводки',
|
||||
captionModel: 'Описание изображений',
|
||||
speechModel: 'Распознавание речи',
|
||||
storage: 'Хранилище',
|
||||
indexes: 'Индексы',
|
||||
name: 'Название',
|
||||
title: 'Заголовок',
|
||||
status: 'Статус',
|
||||
summary: 'Описание',
|
||||
model: 'Модель',
|
||||
mode: 'Режим',
|
||||
url: 'Ссылка',
|
||||
from: 'Откуда',
|
||||
to: 'Куда',
|
||||
folder: 'Папка',
|
||||
page: 'Страница',
|
||||
version: 'Версия',
|
||||
documents: 'Документы',
|
||||
knowledgeBases: 'Базы знаний',
|
||||
mcpServices: 'Сервисы MCP',
|
||||
skills: 'Навыки',
|
||||
webSearch: 'Веб-поиск',
|
||||
multiTurn: 'Многоходовой диалог'
|
||||
},
|
||||
value: {
|
||||
document: 'Документ',
|
||||
faq: 'FAQ',
|
||||
wiki: 'Wiki',
|
||||
on: 'вкл',
|
||||
off: 'выкл',
|
||||
vector: 'Вектор',
|
||||
keyword: 'Ключевые слова',
|
||||
graph: 'Граф',
|
||||
quickAnswer: 'Быстрый ответ',
|
||||
smartReasoning: 'Умное рассуждение',
|
||||
indexSep: ', '
|
||||
}
|
||||
}
|
||||
},
|
||||
kbSettings: {
|
||||
|
|
|
|||
|
|
@ -1969,7 +1969,47 @@ export default {
|
|||
invalidJson: '参数不是合法 JSON',
|
||||
submitted: '已提交',
|
||||
submitFailed: '提交失败',
|
||||
userRejected: '用户拒绝'
|
||||
userRejected: '用户拒绝',
|
||||
detail: {
|
||||
type: '类型',
|
||||
embeddingModel: '嵌入模型',
|
||||
summaryModel: '摘要模型',
|
||||
captionModel: '图片描述',
|
||||
speechModel: '语音识别',
|
||||
storage: '存储',
|
||||
indexes: '索引',
|
||||
name: '名称',
|
||||
title: '标题',
|
||||
status: '状态',
|
||||
summary: '简介',
|
||||
model: '模型',
|
||||
mode: '模式',
|
||||
url: '链接',
|
||||
from: '从',
|
||||
to: '到',
|
||||
folder: '目录',
|
||||
page: '页面',
|
||||
version: '版本',
|
||||
documents: '文档',
|
||||
knowledgeBases: '知识库',
|
||||
mcpServices: 'MCP 服务',
|
||||
skills: '技能',
|
||||
webSearch: '联网搜索',
|
||||
multiTurn: '多轮对话'
|
||||
},
|
||||
value: {
|
||||
document: '文档',
|
||||
faq: '问答',
|
||||
wiki: 'Wiki',
|
||||
on: '开',
|
||||
off: '关',
|
||||
vector: '向量',
|
||||
keyword: '关键词',
|
||||
graph: '图谱',
|
||||
quickAnswer: '快速问答',
|
||||
smartReasoning: '智能推理',
|
||||
indexSep: '、'
|
||||
}
|
||||
}
|
||||
},
|
||||
kbSettings: {
|
||||
|
|
|
|||
|
|
@ -1969,7 +1969,47 @@ export default {
|
|||
invalidJson: '參數不是合法 JSON',
|
||||
submitted: '已提交',
|
||||
submitFailed: '提交失敗',
|
||||
userRejected: '使用者拒絕'
|
||||
userRejected: '使用者拒絕',
|
||||
detail: {
|
||||
type: '類型',
|
||||
embeddingModel: '嵌入模型',
|
||||
summaryModel: '摘要模型',
|
||||
captionModel: '圖片描述',
|
||||
speechModel: '語音識別',
|
||||
storage: '儲存',
|
||||
indexes: '索引',
|
||||
name: '名稱',
|
||||
title: '標題',
|
||||
status: '狀態',
|
||||
summary: '簡介',
|
||||
model: '模型',
|
||||
mode: '模式',
|
||||
url: '連結',
|
||||
from: '從',
|
||||
to: '到',
|
||||
folder: '目錄',
|
||||
page: '頁面',
|
||||
version: '版本',
|
||||
documents: '文件',
|
||||
knowledgeBases: '知識庫',
|
||||
mcpServices: 'MCP 服務',
|
||||
skills: '技能',
|
||||
webSearch: '聯網搜尋',
|
||||
multiTurn: '多輪對話'
|
||||
},
|
||||
value: {
|
||||
document: '文件',
|
||||
faq: '問答',
|
||||
wiki: 'Wiki',
|
||||
on: '開',
|
||||
off: '關',
|
||||
vector: '向量',
|
||||
keyword: '關鍵詞',
|
||||
graph: '圖譜',
|
||||
quickAnswer: '快速問答',
|
||||
smartReasoning: '智能推理',
|
||||
indexSep: '、'
|
||||
}
|
||||
}
|
||||
},
|
||||
kbSettings: {
|
||||
|
|
|
|||
|
|
@ -15,12 +15,12 @@ const parse = description => JSON.parse(JSON.stringify(runInNewContext(
|
|||
test('batch approval retains every title in the separate item list', () => {
|
||||
const titles = Array.from({ length: 20 }, (_, i) => `Document ${i + 1}`)
|
||||
const description = ['Delete documents', 'Finance', ...titles.map(title => '- ' + title)].join('\n')
|
||||
assert.deepEqual(parse(description), { head: 'Delete documents\nFinance', items: titles })
|
||||
assert.deepEqual(parse(description), { head: 'Delete documents\nFinance', fields: [], items: titles })
|
||||
})
|
||||
|
||||
test('legacy multiline titles remain readable through the scrollable fallback', () => {
|
||||
const description = 'Delete documents\nFinance\n- First\ncontinued title\n- Last document'
|
||||
assert.deepEqual(parse(description), { head: description, items: [] })
|
||||
assert.deepEqual(parse(description), { head: description, fields: [], items: [] })
|
||||
assert.match(source, /class="prompt-desc">\{\{ descriptionParts\.head \}\}/)
|
||||
const fallback = styles.match(/\.prompt-desc \{([\s\S]*?)\n\}/)?.[1]
|
||||
assert.ok(fallback)
|
||||
|
|
@ -28,3 +28,26 @@ test('legacy multiline titles remain readable through the scrollable fallback',
|
|||
assert.match(fallback, /overflow-y:\s*auto/)
|
||||
assert.doesNotMatch(fallback, /line-clamp|overflow:\s*hidden/)
|
||||
})
|
||||
|
||||
test('setting lines render as labeled fields and the title stays the headline', () => {
|
||||
const description = [
|
||||
'创建知识库',
|
||||
'助手测试',
|
||||
'Type: document',
|
||||
'Embedding model: builtin-embedding',
|
||||
'Summary model: Qwen',
|
||||
'Indexes: wiki on',
|
||||
].join('\n')
|
||||
assert.deepEqual(parse(description), {
|
||||
head: '创建知识库\n助手测试',
|
||||
fields: [
|
||||
{ label: 'Type', value: 'document' },
|
||||
{ label: 'Embedding model', value: 'builtin-embedding' },
|
||||
{ label: 'Summary model', value: 'Qwen' },
|
||||
{ label: 'Indexes', value: 'wiki on' },
|
||||
],
|
||||
items: [],
|
||||
})
|
||||
assert.match(source, /class="prompt-fields"/)
|
||||
assert.match(styles, /\.prompt-fields \{/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,6 +2,12 @@
|
|||
<div v-if="interactive" class="prompt-panel" @click.stop>
|
||||
<div class="prompt-question">{{ $t('agentStream.toolApproval.dockQuestion', { target: targetLabel }) }}</div>
|
||||
<div v-if="descriptionParts.head" class="prompt-desc">{{ descriptionParts.head }}</div>
|
||||
<dl v-if="descriptionParts.fields.length" class="prompt-fields">
|
||||
<div v-for="(field, i) in descriptionParts.fields" :key="i" class="prompt-field">
|
||||
<dt>{{ approvalFieldLabel(field.label) }}</dt>
|
||||
<dd>{{ approvalFieldValue(field.label, field.value) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<ul v-if="descriptionParts.items.length" class="prompt-desc-items">
|
||||
<li v-for="(item, i) in descriptionParts.items" :key="i">{{ item }}</li>
|
||||
</ul>
|
||||
|
|
@ -147,17 +153,26 @@ const awaitingInDock = computed(() => open.value && props.variant !== 'dock' &&
|
|||
const hasArgs = computed(() => argsText.value.trim().length > 0)
|
||||
|
||||
// A batch operation ends its description with one "- " line per item it acts
|
||||
// on; those render as a list so every item stays visible.
|
||||
// on; those render as a list so every item stays visible. "Label: value"
|
||||
// lines render as a definition list. A broken item list stays one block.
|
||||
const descriptionParts = computed(() => {
|
||||
const lines = (props.description || '').split('\n')
|
||||
const text = (props.description || '').trim()
|
||||
const lines = text ? text.split('\n') : []
|
||||
const start = lines.findIndex((line) => line.startsWith('- '))
|
||||
if (start < 0 || !lines.slice(start).every((line) => line.startsWith('- '))) {
|
||||
return { head: (props.description || '').trim(), items: [] as string[] }
|
||||
const brokenList = start >= 0 && !lines.slice(start).every((line) => line.startsWith('- '))
|
||||
if (!text || brokenList) {
|
||||
return { head: text, fields: [], items: [] }
|
||||
}
|
||||
return {
|
||||
head: lines.slice(0, start).join('\n').trim(),
|
||||
items: lines.slice(start).map((line) => line.slice(2)),
|
||||
const body = start < 0 ? lines : lines.slice(0, start)
|
||||
const items = start < 0 ? [] : lines.slice(start).map((line) => line.slice(2))
|
||||
const fields = []
|
||||
const headLines = []
|
||||
for (const line of body) {
|
||||
const match = /^([^:\n]{1,48}): (.+)$/.exec(line)
|
||||
if (match) fields.push({ label: match[1], value: match[2] })
|
||||
else headLines.push(line)
|
||||
}
|
||||
return { head: headLines.join('\n').trim(), fields, items }
|
||||
})
|
||||
|
||||
const isJsonValid = computed(() => {
|
||||
|
|
@ -170,6 +185,68 @@ const isJsonValid = computed(() => {
|
|||
}
|
||||
})
|
||||
|
||||
const approvalDetailKey: Record<string, string> = {
|
||||
Type: 'type',
|
||||
'Embedding model': 'embeddingModel',
|
||||
'Summary model': 'summaryModel',
|
||||
'Caption model': 'captionModel',
|
||||
'Speech model': 'speechModel',
|
||||
Storage: 'storage',
|
||||
Indexes: 'indexes',
|
||||
Name: 'name',
|
||||
Title: 'title',
|
||||
Status: 'status',
|
||||
Summary: 'summary',
|
||||
Model: 'model',
|
||||
Mode: 'mode',
|
||||
URL: 'url',
|
||||
From: 'from',
|
||||
To: 'to',
|
||||
Folder: 'folder',
|
||||
Page: 'page',
|
||||
Version: 'version',
|
||||
Documents: 'documents',
|
||||
'Knowledge bases': 'knowledgeBases',
|
||||
'MCP services': 'mcpServices',
|
||||
Skills: 'skills',
|
||||
'Web search': 'webSearch',
|
||||
'Multi-turn conversation': 'multiTurn',
|
||||
}
|
||||
|
||||
const approvalValueKey: Record<string, string> = {
|
||||
document: 'document',
|
||||
faq: 'faq',
|
||||
wiki: 'wiki',
|
||||
on: 'on',
|
||||
off: 'off',
|
||||
vector: 'vector',
|
||||
keyword: 'keyword',
|
||||
graph: 'graph',
|
||||
'quick-answer': 'quickAnswer',
|
||||
'smart-reasoning': 'smartReasoning',
|
||||
}
|
||||
|
||||
function approvalFieldLabel(label: string) {
|
||||
const key = approvalDetailKey[label]
|
||||
return key ? t(`agentStream.toolApproval.detail.${key}`) : label
|
||||
}
|
||||
|
||||
function approvalToken(token: string) {
|
||||
const key = approvalValueKey[token]
|
||||
return key ? t(`agentStream.toolApproval.value.${key}`) : token
|
||||
}
|
||||
|
||||
function approvalFieldValue(label: string, value: string) {
|
||||
if (label === 'Indexes') {
|
||||
const parts = value.split(', ').map((part) => part.split(' ').map(approvalToken).join(' '))
|
||||
return parts.join(t('agentStream.toolApproval.value.indexSep'))
|
||||
}
|
||||
if (label === 'Type' || label === 'Mode' || value === 'on' || value === 'off') {
|
||||
return approvalToken(value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
const argsDirty = computed(() => argsText.value.trim() !== initialArgs.trim())
|
||||
|
||||
const headerIcon = computed(() => {
|
||||
|
|
|
|||
|
|
@ -282,6 +282,36 @@
|
|||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.prompt-fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin: -2px 0 0;
|
||||
max-height: calc(1.4em * 6 + 20px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.prompt-field {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
column-gap: 12px;
|
||||
align-items: baseline;
|
||||
margin: 0;
|
||||
font-size: var(--agent-step-summary-size, 13px);
|
||||
line-height: 1.4;
|
||||
|
||||
dt {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.prompt-desc-items {
|
||||
margin: -4px 0 0;
|
||||
padding-left: 18px;
|
||||
|
|
|
|||
|
|
@ -544,3 +544,68 @@ func TestBuiltinAgentSkillParams(t *testing.T) {
|
|||
require.Error(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuiltinKnowledgeBaseLifecycle(t *testing.T) {
|
||||
catalog := Builtin()
|
||||
create, ok := catalog.Get("knowledge_base.create")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "name", create.LabelParam)
|
||||
name, ok := create.Param("name")
|
||||
require.True(t, ok)
|
||||
assert.True(t, name.Required)
|
||||
_, ok = create.Param("knowledge_base_id")
|
||||
assert.False(t, ok)
|
||||
_, ok = create.Param("indexing_strategy")
|
||||
assert.False(t, ok)
|
||||
vector, ok := create.Param("vector_enabled")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, TypeBoolean, vector.Type)
|
||||
_, ok = create.Param("embedding_model_id")
|
||||
assert.True(t, ok)
|
||||
_, ok = create.Param("chunk_size")
|
||||
assert.True(t, ok)
|
||||
_, ok = create.Param("vector_store_id")
|
||||
assert.True(t, ok)
|
||||
kind, ok := create.Param("type")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, []string{"document", "faq", "wiki"}, kind.Enum)
|
||||
|
||||
update, ok := catalog.Get("knowledge_base.update")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, http.MethodPatch, update.Method)
|
||||
_, ok = update.Param("name")
|
||||
assert.True(t, ok)
|
||||
_, ok = update.Param("description")
|
||||
assert.True(t, ok)
|
||||
_, ok = update.Param("vector_enabled")
|
||||
assert.True(t, ok)
|
||||
_, ok = update.Param("embedding_model_id")
|
||||
assert.True(t, ok)
|
||||
_, ok = update.Param("chunk_size")
|
||||
assert.True(t, ok)
|
||||
_, ok = update.Param("vector_store_id")
|
||||
assert.False(t, ok, "the vector store is chosen when the knowledge base is created")
|
||||
|
||||
del, ok := catalog.Get("knowledge_base.delete")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, RiskDestructive, del.Risk)
|
||||
|
||||
setTags, ok := catalog.Get("knowledge.set_tags")
|
||||
require.True(t, ok)
|
||||
docs, ok := setTags.Param("knowledge_ids")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, TypeStringList, docs.Type)
|
||||
assert.Equal(t, 20, docs.MaxItems)
|
||||
tags, ok := setTags.Param("tag_ids")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, 50, tags.MaxItems)
|
||||
require.NotNil(t, setTags.Target)
|
||||
require.NotNil(t, setTags.Target.Items)
|
||||
assert.Equal(t, "knowledge_ids", setTags.Target.Items.Param)
|
||||
|
||||
manual, ok := catalog.Get("knowledge.update_manual")
|
||||
require.True(t, ok)
|
||||
content, ok := manual.Param("content")
|
||||
require.True(t, ok)
|
||||
assert.True(t, content.Required)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,7 +112,9 @@ func (op Operation) Build(params map[string]json.RawMessage) (Call, error) {
|
|||
query.Set(p.wireKey(), strconv.FormatBool(v))
|
||||
}
|
||||
case InBody:
|
||||
body[p.wireKey()] = value
|
||||
if err := assignBody(body, p.wireKey(), value); err != nil {
|
||||
return Call{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -130,6 +132,35 @@ func (op Operation) Build(params map[string]json.RawMessage) (Call, error) {
|
|||
return call, nil
|
||||
}
|
||||
|
||||
// assignBody writes value at a dotted JSON path, creating objects along the way.
|
||||
func assignBody(body map[string]any, key string, value any) error {
|
||||
parts := strings.Split(key, ".")
|
||||
cursor := body
|
||||
for _, part := range parts[:len(parts)-1] {
|
||||
if part == "" {
|
||||
return fmt.Errorf("body field %q has an empty path segment", key)
|
||||
}
|
||||
existing, ok := cursor[part]
|
||||
if !ok {
|
||||
next := map[string]any{}
|
||||
cursor[part] = next
|
||||
cursor = next
|
||||
continue
|
||||
}
|
||||
next, ok := existing.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("body field %q conflicts with another field", key)
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
leaf := parts[len(parts)-1]
|
||||
if leaf == "" {
|
||||
return fmt.Errorf("body field %q has an empty path segment", key)
|
||||
}
|
||||
cursor[leaf] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// SelectParams keeps the parameters op accepts.
|
||||
func SelectParams(op Operation, params map[string]json.RawMessage) map[string]json.RawMessage {
|
||||
out := make(map[string]json.RawMessage, len(op.Params))
|
||||
|
|
|
|||
|
|
@ -46,6 +46,10 @@ const (
|
|||
// single object, so a long field (a prompt, say) does not repeat on
|
||||
// every item of a list.
|
||||
extAgentDetail = "x-agent-detail"
|
||||
// extAgentResponse keeps a field in responses and out of request
|
||||
// parameters. Identifiers and computed counts are projected when the
|
||||
// model reads an object, and are not something it may set on create.
|
||||
extAgentResponse = "x-agent-response"
|
||||
)
|
||||
|
||||
// agentItems is ItemTarget as written in x-agent:
|
||||
|
|
@ -135,6 +139,8 @@ type specSchema struct {
|
|||
AgentMaxBytes string `json:"x-agent-max-bytes"`
|
||||
AgentMaxRunes string `json:"x-agent-max-runes"`
|
||||
AgentDetail bool `json:"x-agent-detail"`
|
||||
// AgentResponse projects the field and does not accept it as a parameter.
|
||||
AgentResponse bool `json:"x-agent-response"`
|
||||
// AgentRequired makes an API-optional field mandatory for the model.
|
||||
AgentRequired bool `json:"x-agent-required"`
|
||||
}
|
||||
|
|
@ -325,6 +331,28 @@ func (doc *specDocument) bodyParams(sp specParameter) ([]Param, error) {
|
|||
var out []Param
|
||||
for _, key := range sortedKeys(obj.Properties) {
|
||||
prop := obj.Properties[key]
|
||||
shape, err := doc.resolve(prop)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// An object is not one parameter. Its tagged scalars are, and the
|
||||
// wire key keeps the path so the request nests them again.
|
||||
if shape != nil && shape.Type != "array" && (shape.Type == "object" || len(shape.Properties) > 0) {
|
||||
nested, err := doc.flattenBodyObject(shape, key, sp.Required)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nested) > 0 {
|
||||
out = append(out, nested...)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if prop.AgentResponse {
|
||||
if sp.Required && required[key] {
|
||||
return nil, fmt.Errorf("body field %q is required but marked %s", key, extAgentResponse)
|
||||
}
|
||||
continue
|
||||
}
|
||||
name, exposed, err := agentName(prop.Agent, key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("body field %q: %w", key, err)
|
||||
|
|
@ -343,12 +371,65 @@ func (doc *specDocument) bodyParams(sp specParameter) ([]Param, error) {
|
|||
AllowEmpty: prop.AgentRequired && !required[key],
|
||||
Description: strings.TrimSpace(prop.Description),
|
||||
}
|
||||
if err := doc.typeParam(&p, shape, prop.AgentMax, prop.AgentMaxBytes); err != nil {
|
||||
return nil, fmt.Errorf("body field %q: %w", key, err)
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// flattenBodyObject turns the tagged scalars inside an object into body
|
||||
// parameters. The wire key is the dotted JSON path.
|
||||
func (doc *specDocument) flattenBodyObject(obj *specSchema, prefix string, bodyRequired bool) ([]Param, error) {
|
||||
required := map[string]bool{}
|
||||
for _, key := range obj.Required {
|
||||
required[key] = true
|
||||
}
|
||||
var out []Param
|
||||
for _, key := range sortedKeys(obj.Properties) {
|
||||
prop := obj.Properties[key]
|
||||
path := prefix + "." + key
|
||||
shape, err := doc.resolve(prop)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if shape != nil && shape.Type != "array" && (shape.Type == "object" || len(shape.Properties) > 0) {
|
||||
nested, err := doc.flattenBodyObject(shape, path, bodyRequired)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nested) > 0 {
|
||||
out = append(out, nested...)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if prop.AgentResponse {
|
||||
if bodyRequired && required[key] {
|
||||
return nil, fmt.Errorf("body field %q is required but marked %s", path, extAgentResponse)
|
||||
}
|
||||
continue
|
||||
}
|
||||
name, exposed, err := agentName(prop.Agent, key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("body field %q: %w", path, err)
|
||||
}
|
||||
if !exposed {
|
||||
if bodyRequired && required[key] {
|
||||
return nil, fmt.Errorf("body field %q is required but not exposed with %s", path, extAgent)
|
||||
}
|
||||
continue
|
||||
}
|
||||
p := Param{
|
||||
Name: name,
|
||||
In: InBody,
|
||||
Key: path,
|
||||
Required: bodyRequired && (required[key] || prop.AgentRequired),
|
||||
AllowEmpty: prop.AgentRequired && !required[key],
|
||||
Description: strings.TrimSpace(prop.Description),
|
||||
}
|
||||
if err := doc.typeParam(&p, shape, prop.AgentMax, prop.AgentMaxBytes); err != nil {
|
||||
return nil, fmt.Errorf("body field %q: %w", key, err)
|
||||
return nil, fmt.Errorf("body field %q: %w", path, err)
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -225,6 +225,76 @@ func TestFromSpecAgentRequired(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestFromSpecSkipsResponseOnlyBodyFields(t *testing.T) {
|
||||
spec := `{
|
||||
"paths": {
|
||||
"/api/v1/knowledge-bases": {
|
||||
"post": {
|
||||
"summary": "Create",
|
||||
"parameters": [{"name": "body", "in": "body", "required": true, "schema": {"$ref": "#/definitions/KB"}}],
|
||||
"responses": {"201": {"schema": {"$ref": "#/definitions/KB"}}},
|
||||
"x-agent": {"id": "knowledge_base.create", "risk": "write", "label_param": "name"},
|
||||
"x-agent-hint": "Creates one."
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"KB": {
|
||||
"type": "object",
|
||||
"required": ["name"],
|
||||
"properties": {
|
||||
"name": {"type": "string", "description": "Name", "x-agent": true},
|
||||
"id": {"type": "string", "description": "ID", "x-agent": "knowledge_base_id", "x-agent-response": true},
|
||||
"indexing_strategy": {
|
||||
"type": "object",
|
||||
"description": "Indexing",
|
||||
"x-agent": true,
|
||||
"x-agent-response": true,
|
||||
"properties": {"vector": {"type": "boolean", "description": "Vector", "x-agent": true}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
ops, err := FromSpec([]byte(spec))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, ops, 1)
|
||||
assert.ElementsMatch(t, []string{"name", "vector"}, paramNames(ops[0]))
|
||||
_, ok := ops[0].Param("knowledge_base_id")
|
||||
assert.False(t, ok, "a response-only identifier is not a create parameter")
|
||||
_, ok = ops[0].Param("indexing_strategy")
|
||||
assert.False(t, ok, "the indexing object itself is not a parameter")
|
||||
vector, ok := ops[0].Param("vector")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "indexing_strategy.vector", vector.Key)
|
||||
call, err := ops[0].Build(map[string]json.RawMessage{
|
||||
"name": json.RawMessage(`"产品文档"`),
|
||||
"vector": json.RawMessage(`true`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.JSONEq(t, `{"name":"产品文档","indexing_strategy":{"vector":true}}`, string(call.Body))
|
||||
id, ok := fieldByFrom(ops[0].Result.Fields, "id")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "knowledge_base_id", id.As)
|
||||
}
|
||||
|
||||
func paramNames(op Operation) []string {
|
||||
names := make([]string, 0, len(op.Params))
|
||||
for _, p := range op.Params {
|
||||
names = append(names, p.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func fieldByFrom(fields []Field, from string) (Field, bool) {
|
||||
for _, field := range fields {
|
||||
if field.From == from {
|
||||
return field, true
|
||||
}
|
||||
}
|
||||
return Field{}, false
|
||||
}
|
||||
|
||||
func TestFromSpecMarksCatchAllSegment(t *testing.T) {
|
||||
spec := strings.Replace(testSpec,
|
||||
`{"id": "doc.get", "risk": "read"}`, `{"id": "doc.get", "risk": "read", "catch_all": "id"}`, 1)
|
||||
|
|
|
|||
|
|
@ -690,6 +690,40 @@ func mutationDetail(
|
|||
if s, ok := rawString(params, "title"); ok && s != "" {
|
||||
lines = append(lines, "Title: "+excerpt(s))
|
||||
}
|
||||
if s, ok := rawString(params, "type"); ok && s != "" {
|
||||
lines = append(lines, "Type: "+s)
|
||||
}
|
||||
for _, field := range []struct{ param, label string }{
|
||||
{"embedding_model_id", "Embedding model"},
|
||||
{"summary_model_id", "Summary model"},
|
||||
{"vlm_model_id", "Caption model"},
|
||||
{"asr_model_id", "Speech model"},
|
||||
} {
|
||||
if s, ok := rawString(params, field.param); ok && s != "" {
|
||||
lines = append(lines, field.label+": "+resolvedLabels(ctx, t, modelLabels, []string{s}, identity))
|
||||
}
|
||||
}
|
||||
if s, ok := rawString(params, "storage_backend_id"); ok && s != "" {
|
||||
lines = append(lines, "Storage: "+s)
|
||||
}
|
||||
var indexes []string
|
||||
for _, flag := range []struct{ param, token string }{
|
||||
{"vector_enabled", "vector"},
|
||||
{"keyword_enabled", "keyword"},
|
||||
{"wiki_enabled", "wiki"},
|
||||
{"graph_enabled", "graph"},
|
||||
} {
|
||||
if on, ok := rawBool(params, flag.param); ok {
|
||||
state := "off"
|
||||
if on {
|
||||
state = "on"
|
||||
}
|
||||
indexes = append(indexes, flag.token+" "+state)
|
||||
}
|
||||
}
|
||||
if len(indexes) > 0 {
|
||||
lines = append(lines, "Indexes: "+strings.Join(indexes, ", "))
|
||||
}
|
||||
if s, ok := rawString(params, "status"); ok && s != "" {
|
||||
lines = append(lines, "Status: "+s)
|
||||
}
|
||||
|
|
@ -731,20 +765,22 @@ func mutationDetail(
|
|||
lines = append(lines, "Documents: "+resolvedLabels(ctx, t, knowledgeLabels, ids, identity))
|
||||
}
|
||||
}
|
||||
lines = append(lines, agentSettingsDetail(ctx, t, params, identity)...)
|
||||
lines = append(lines, agentSettingsDetail(ctx, t, op, params, identity)...)
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// agentSettingsDetail lists the agent settings a call sets, with models,
|
||||
// knowledge bases and MCP services by name.
|
||||
// knowledge bases and MCP services by name. A create already shows name as
|
||||
// the card title, so that line is not repeated.
|
||||
func agentSettingsDetail(
|
||||
ctx context.Context,
|
||||
t *RunOperationTool,
|
||||
op operations.Operation,
|
||||
params map[string]json.RawMessage,
|
||||
identity operations.Identity,
|
||||
) []string {
|
||||
var lines []string
|
||||
if s, ok := rawString(params, "name"); ok && s != "" {
|
||||
if s, ok := rawString(params, "name"); ok && s != "" && op.LabelParam != "name" {
|
||||
lines = append(lines, "Name: "+excerpt(s))
|
||||
}
|
||||
if s, ok := rawString(params, "agent_mode"); ok && s != "" {
|
||||
|
|
|
|||
|
|
@ -402,7 +402,7 @@ func TestRunOperationAgentApprovals(t *testing.T) {
|
|||
res, _ := tool.Execute(interactiveCtx(), runArgs("agent.create", map[string]any{"name": "Release\nnotes"}))
|
||||
require.True(t, res.Success, res.Error)
|
||||
require.Len(t, gate.requests, 1)
|
||||
assert.Equal(t, "创建智能体\nRelease notes\nName: Release notes", gate.requests[0].Description)
|
||||
assert.Equal(t, "创建智能体\nRelease notes", gate.requests[0].Description)
|
||||
assert.Contains(t, res.Output, `"agent_id":"a1"`)
|
||||
|
||||
gate.requests = nil
|
||||
|
|
@ -424,6 +424,35 @@ func TestRunOperationAgentApprovals(t *testing.T) {
|
|||
`"system_prompt":"Answer in English.","web_search_enabled":false}`, string(d.calls[len(d.calls)-1].call.Body))
|
||||
}
|
||||
|
||||
func TestRunOperationKnowledgeBaseCreateApproval(t *testing.T) {
|
||||
d := &fakeDispatcher{responses: map[string]*operations.Response{
|
||||
"GET /api/v1/models/emb": {
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"data":{"id":"emb","name":"builtin-embedding","display_name":"builtin-embedding"}}`),
|
||||
},
|
||||
"GET /api/v1/models/sum": {
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"data":{"id":"sum","name":"qwen","display_name":"Qwen"}}`),
|
||||
},
|
||||
"POST /api/v1/knowledge-bases": {
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"data":{"id":"kb","name":"助手测试"}}`),
|
||||
},
|
||||
}}
|
||||
gate := &fakeApprover{decision: approval.Decision{Approved: true, PendingID: "p1"}}
|
||||
res, _ := newRunTool(d, gate).Execute(interactiveCtx(), runArgs("knowledge_base.create", map[string]any{
|
||||
"name": "助手测试", "type": "document",
|
||||
"embedding_model_id": "emb", "summary_model_id": "sum",
|
||||
"vlm_model_id": "builtin-vllm", "wiki_enabled": true,
|
||||
}))
|
||||
require.True(t, res.Success, res.Error)
|
||||
require.Len(t, gate.requests, 1)
|
||||
assert.Equal(t,
|
||||
"创建知识库\n助手测试\nType: document\nEmbedding model: builtin-embedding\n"+
|
||||
"Summary model: Qwen\nCaption model: builtin-vllm\nIndexes: wiki on",
|
||||
gate.requests[0].Description)
|
||||
}
|
||||
|
||||
func TestRunOperationAgentUpdateRefusesTruncatedPrompt(t *testing.T) {
|
||||
long, err := json.Marshal(map[string]any{"data": map[string]any{
|
||||
"id": "a1", "name": "Support", "config": map[string]any{"system_prompt": string(make([]rune, 8001))},
|
||||
|
|
|
|||
|
|
@ -619,6 +619,10 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
|||
profileWasEnabled = kb.ProfileConfig.IsEnabled()
|
||||
kb.ProfileConfig = config.ProfileConfig
|
||||
}
|
||||
if config.ExtractConfig != nil {
|
||||
kb.ExtractConfig = config.ExtractConfig
|
||||
changedFields = append(changedFields, "extract_config")
|
||||
}
|
||||
// Update indexing strategy — syncs to ExtractConfig for backward compat
|
||||
if config.IndexingStrategy != nil {
|
||||
if !config.IndexingStrategy.HasAnyIndexing() {
|
||||
|
|
@ -637,6 +641,49 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
|||
kb.ExtractConfig = &types.ExtractConfig{Enabled: true}
|
||||
}
|
||||
}
|
||||
if config.EmbeddingModelID != nil {
|
||||
next := strings.TrimSpace(*config.EmbeddingModelID)
|
||||
if next != kb.EmbeddingModelID {
|
||||
if err := s.rejectEmbeddingModelChange(ctx, kb, next); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
changedFields = append(changedFields, "embedding_model_id")
|
||||
kb.EmbeddingModelID = next
|
||||
}
|
||||
}
|
||||
if config.SummaryModelID != nil {
|
||||
next := strings.TrimSpace(*config.SummaryModelID)
|
||||
if err := s.requireModelType(ctx, next, types.ModelTypeKnowledgeQA, "summary_model_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if kb.SummaryModelID != next {
|
||||
changedFields = append(changedFields, "summary_model_id")
|
||||
}
|
||||
kb.SummaryModelID = next
|
||||
}
|
||||
if config.StorageBackendID != nil {
|
||||
changed, err := s.updateStorageBackend(ctx, kb, *config.StorageBackendID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if changed {
|
||||
changedFields = append(changedFields, "storage_backend_id")
|
||||
}
|
||||
}
|
||||
if config.ASRConfig != nil {
|
||||
if config.ASRConfig.Enabled {
|
||||
modelID := strings.TrimSpace(config.ASRConfig.ModelID)
|
||||
if err := s.requireModelType(ctx, modelID, types.ModelTypeASR, "asr_model_id"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
kb.ASRConfig = *config.ASRConfig
|
||||
changedFields = append(changedFields, "asr_config")
|
||||
}
|
||||
if config.QuestionGenerationConfig != nil {
|
||||
kb.QuestionGenerationConfig = config.QuestionGenerationConfig
|
||||
changedFields = append(changedFields, "question_generation_config")
|
||||
}
|
||||
}
|
||||
// Apply multimodal (vision) config only when the caller provided it,
|
||||
// mirroring the nil-means-no-change semantics used above.
|
||||
|
|
@ -674,6 +721,81 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
|||
return kb, nil
|
||||
}
|
||||
|
||||
// updateStorageBackend preserves existing file locations. Echoing a binding is
|
||||
// a no-op, including for shared KBs whose storage belongs to another workspace.
|
||||
func (s *knowledgeBaseService) updateStorageBackend(
|
||||
ctx context.Context, kb *types.KnowledgeBase, id string,
|
||||
) (bool, error) {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return false, apperrors.NewBadRequestError("storage_backend_id cannot be empty")
|
||||
}
|
||||
if kb.StorageBackendID != nil && strings.TrimSpace(*kb.StorageBackendID) == id {
|
||||
return false, nil
|
||||
}
|
||||
if types.CallerFromContext(ctx).TenantID != kb.TenantID {
|
||||
return false, apperrors.NewForbiddenError("只有知识库所属空间可以修改存储配置")
|
||||
}
|
||||
total, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, kb.TenantID, kb.ID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check files before changing storage backend: %w", err)
|
||||
}
|
||||
if total > 0 {
|
||||
return false, apperrors.NewBadRequestError(
|
||||
"Storage backend cannot be changed while the knowledge base contains files; migrate storage first")
|
||||
}
|
||||
next := *kb
|
||||
next.StorageBackendID = &id
|
||||
if err := s.applyAndValidateStorageBackend(ctx, &next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
kb.StorageBackendID = next.StorageBackendID
|
||||
kb.StorageProviderConfig = next.StorageProviderConfig
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeBaseService) rejectEmbeddingModelChange(
|
||||
ctx context.Context, kb *types.KnowledgeBase, next string,
|
||||
) error {
|
||||
if next == "" {
|
||||
return apperrors.NewBadRequestError("embedding_model_id cannot be empty")
|
||||
}
|
||||
if err := s.requireModelType(ctx, next, types.ModelTypeEmbedding, "embedding_model_id"); err != nil {
|
||||
return err
|
||||
}
|
||||
if kb.EmbeddingModelID == "" {
|
||||
return nil
|
||||
}
|
||||
_, total, err := s.kgRepo.ListPagedKnowledgeByKnowledgeBaseID(ctx, kb.TenantID, kb.ID,
|
||||
&types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if total > 0 {
|
||||
return apperrors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *knowledgeBaseService) requireModelType(
|
||||
ctx context.Context, id string, want types.ModelType, field string,
|
||||
) error {
|
||||
if strings.TrimSpace(id) == "" {
|
||||
return apperrors.NewBadRequestError(field + " cannot be empty")
|
||||
}
|
||||
if s.modelService == nil {
|
||||
return apperrors.NewInternalServerError("model service is not configured")
|
||||
}
|
||||
model, err := s.modelService.GetModelByID(ctx, id)
|
||||
if err != nil || model == nil {
|
||||
return apperrors.NewBadRequestError(field + " does not match a model")
|
||||
}
|
||||
if model.Type != want {
|
||||
return apperrors.NewBadRequestError(field + " must be a " + string(want) + " model")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TogglePinKnowledgeBase toggles whether the calling user has pinned
|
||||
// this knowledge base. Pin state is per-(user, kb) as of migration
|
||||
// 000050; previously this method flipped a tenant-wide column on the
|
||||
|
|
|
|||
|
|
@ -0,0 +1,150 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type storageUpdateKBRepo struct {
|
||||
interfaces.KnowledgeBaseRepository
|
||||
kb types.KnowledgeBase
|
||||
saves int
|
||||
}
|
||||
|
||||
func (r *storageUpdateKBRepo) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
|
||||
kb := r.kb
|
||||
return &kb, nil
|
||||
}
|
||||
|
||||
func (r *storageUpdateKBRepo) UpdateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
|
||||
r.kb = *kb
|
||||
r.saves++
|
||||
return nil
|
||||
}
|
||||
|
||||
type storageUpdateKnowledgeRepo struct {
|
||||
interfaces.KnowledgeRepository
|
||||
t *testing.T
|
||||
total int64
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *storageUpdateKnowledgeRepo) CountKnowledgeByKnowledgeBaseID(
|
||||
_ context.Context, tenantID uint64, id string,
|
||||
) (int64, error) {
|
||||
require.Equal(r.t, uint64(1), tenantID)
|
||||
require.Equal(r.t, "kb-1", id)
|
||||
r.calls++
|
||||
return r.total, r.err
|
||||
}
|
||||
|
||||
type storageUpdateResolver struct {
|
||||
interfaces.StorageBackendResolver
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *storageUpdateResolver) ResolveBackend(
|
||||
_ context.Context, tenant *types.Tenant, id, _ string,
|
||||
) (*types.StorageBackend, error) {
|
||||
r.calls++
|
||||
return &types.StorageBackend{ID: id, TenantID: tenant.ID, Provider: "s3"}, r.err
|
||||
}
|
||||
|
||||
func TestUpdateKnowledgeBaseStorageBinding(t *testing.T) {
|
||||
countErr := errors.New("cannot count documents")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
oldID string
|
||||
nextID string
|
||||
callerTenant uint64
|
||||
total int64
|
||||
countErr error
|
||||
resolveErr error
|
||||
wantHTTP int
|
||||
wantCounts int
|
||||
wantResolves int
|
||||
}{
|
||||
{name: "empty KB", oldID: "old", nextID: "new", callerTenant: 1, wantCounts: 1, wantResolves: 1},
|
||||
{name: "initial binding", nextID: "new", callerTenant: 1, wantCounts: 1, wantResolves: 1},
|
||||
{
|
||||
name: "existing files", oldID: "old", nextID: "new", callerTenant: 1,
|
||||
total: 1, wantHTTP: http.StatusBadRequest, wantCounts: 1,
|
||||
},
|
||||
{
|
||||
name: "legacy files", nextID: "new", callerTenant: 1,
|
||||
total: 1, wantHTTP: http.StatusBadRequest, wantCounts: 1,
|
||||
},
|
||||
{
|
||||
name: "count failure", oldID: "old", nextID: "new", callerTenant: 1,
|
||||
countErr: countErr, wantCounts: 1,
|
||||
},
|
||||
{
|
||||
name: "same binding with files", oldID: "old", nextID: " old ", callerTenant: 1, total: 1,
|
||||
},
|
||||
{
|
||||
name: "share admin echo", oldID: "old", nextID: "old", callerTenant: 2, total: 1,
|
||||
},
|
||||
{
|
||||
name: "share admin rebind", oldID: "old", nextID: "new", callerTenant: 2,
|
||||
wantHTTP: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "unavailable backend", oldID: "old", nextID: "new", callerTenant: 1,
|
||||
resolveErr: errors.New("not found"), wantHTTP: http.StatusBadRequest, wantCounts: 1, wantResolves: 1,
|
||||
},
|
||||
{name: "empty ID", oldID: "old", callerTenant: 1, wantHTTP: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stored := types.KnowledgeBase{ID: "kb-1", TenantID: 1, Name: "before"}
|
||||
stored.SetStorageProvider("local")
|
||||
if tc.oldID != "" {
|
||||
stored.StorageBackendID = &tc.oldID
|
||||
}
|
||||
repo := &storageUpdateKBRepo{kb: stored}
|
||||
knowledge := &storageUpdateKnowledgeRepo{t: t, total: tc.total, err: tc.countErr}
|
||||
resolver := &storageUpdateResolver{err: tc.resolveErr}
|
||||
svc := &knowledgeBaseService{repo: repo, kgRepo: knowledge, storageResolver: resolver}
|
||||
ctx := types.WithCaller(context.Background(), types.Caller{TenantID: tc.callerTenant})
|
||||
ctx = types.WithExecutionTenant(ctx, 1)
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, &types.Tenant{ID: tc.callerTenant})
|
||||
updated, err := svc.UpdateKnowledgeBase(ctx, stored.ID, "after", "", &types.KnowledgeBaseConfig{
|
||||
StorageBackendID: &tc.nextID,
|
||||
}, nil)
|
||||
if tc.countErr != nil || tc.wantHTTP != 0 {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, updated)
|
||||
require.Zero(t, repo.saves)
|
||||
require.Equal(t, stored, repo.kb, "a rejected update must not change persisted configuration")
|
||||
if tc.countErr != nil {
|
||||
require.ErrorIs(t, err, tc.countErr)
|
||||
} else {
|
||||
appErr, ok := apperrors.IsAppError(err)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, tc.wantHTTP, appErr.HTTPCode)
|
||||
}
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, repo.saves)
|
||||
require.Equal(t, "after", updated.Name)
|
||||
if tc.wantResolves > 0 {
|
||||
require.Equal(t, tc.nextID, *updated.StorageBackendID)
|
||||
require.Equal(t, "s3", updated.GetStorageProvider())
|
||||
} else {
|
||||
require.Equal(t, stored.StorageBackendID, updated.StorageBackendID)
|
||||
require.Equal(t, "local", updated.GetStorageProvider())
|
||||
}
|
||||
}
|
||||
require.Equal(t, tc.wantCounts, knowledge.calls)
|
||||
require.Equal(t, tc.wantResolves, resolver.calls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -578,7 +578,7 @@ func (h *KnowledgeHandler) CreateKnowledgeFromURL(c *gin.Context) {
|
|||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge.create_manual","risk":"write","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Creates a Markdown document. status=draft (the default) keeps it out of search; publish indexes it."
|
||||
// @x-agent-hint "Creates a Markdown document. Send the full content, and status draft to keep it out of search or publish to index it."
|
||||
// @Router /knowledge-bases/{id}/knowledge/manual [post]
|
||||
func (h *KnowledgeHandler) CreateManualKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
@ -2474,12 +2474,14 @@ func (h *KnowledgeHandler) RegenerateKnowledgeSummary(c *gin.Context) {
|
|||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识ID"
|
||||
// @Param id path string true "知识ID" extensions(x-agent=knowledge_id)
|
||||
// @Param request body types.ManualKnowledgePayload true "手工知识内容"
|
||||
// @Success 200 {object} handler.DataResponse{data=types.Knowledge} "更新后的知识"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge.update_manual","risk":"write","target":"knowledge.get","label":"title"}
|
||||
// @x-agent-hint "Replaces the whole Markdown of a document created as manual knowledge. Send the complete content, not a diff. status draft keeps it out of search; publish indexes it. Uploaded files cannot be edited this way."
|
||||
// @Router /knowledge/manual/{id} [put]
|
||||
func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
@ -2655,22 +2657,76 @@ func (h *KnowledgeHandler) CancelKnowledgeParse(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
type knowledgeTagBatchRequest struct {
|
||||
Updates map[string][]string `json:"updates" binding:"required,min=1"`
|
||||
KBID string `json:"kb_id"` // Optional: scope to this KB (validates editor access and uses effective tenant for shared KB)
|
||||
// KnowledgeTagBatchRequest sets tags on documents. The editor sends updates;
|
||||
// the assistant sends knowledge_ids and tag_ids for one knowledge base.
|
||||
type KnowledgeTagBatchRequest struct {
|
||||
// Map of knowledge id to the tag ids that replace its current tags.
|
||||
Updates map[string][]string `json:"updates"`
|
||||
// Knowledge base the documents belong to.
|
||||
KBID string `json:"kb_id" extensions:"x-agent=knowledge_base_id,x-agent-required"`
|
||||
// Documents that receive the same tags. Mutually exclusive with updates.
|
||||
KnowledgeIDs []string `json:"knowledge_ids" extensions:"x-agent,x-agent-required,x-agent-maximum=20"`
|
||||
// Tags to set on every listed document. An empty list clears them.
|
||||
TagIDs []string `json:"tag_ids" extensions:"x-agent,x-agent-required,x-agent-maximum=50"`
|
||||
}
|
||||
|
||||
const (
|
||||
maxKnowledgeTagBatchDocuments = 20
|
||||
maxKnowledgeTagBatchTags = 50
|
||||
)
|
||||
|
||||
// applyKnowledgeTagBatch turns the list form into the updates map the
|
||||
// service already stores. An omitted tag_ids with knowledge_ids is refused
|
||||
// so a partial body cannot clear tags by accident; an empty list still clears.
|
||||
func applyKnowledgeTagBatch(req *KnowledgeTagBatchRequest) error {
|
||||
if len(req.KnowledgeIDs) == 0 {
|
||||
if len(req.Updates) == 0 {
|
||||
return errors.NewBadRequestError("updates is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(req.Updates) > 0 {
|
||||
return errors.NewBadRequestError("knowledge_ids and updates cannot both be set")
|
||||
}
|
||||
if req.TagIDs == nil {
|
||||
return errors.NewBadRequestError("tag_ids is required when knowledge_ids is set")
|
||||
}
|
||||
if len(req.KnowledgeIDs) > maxKnowledgeTagBatchDocuments {
|
||||
return errors.NewBadRequestError("at most 20 documents")
|
||||
}
|
||||
if len(req.TagIDs) > maxKnowledgeTagBatchTags {
|
||||
return errors.NewBadRequestError("at most 50 tags")
|
||||
}
|
||||
seen := make(map[string]struct{}, len(req.KnowledgeIDs))
|
||||
updates := make(map[string][]string, len(req.KnowledgeIDs))
|
||||
for _, id := range req.KnowledgeIDs {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" {
|
||||
return errors.NewBadRequestError("knowledge id cannot be empty")
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
return errors.NewBadRequestError("duplicate knowledge id")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
updates[id] = req.TagIDs
|
||||
}
|
||||
req.Updates = updates
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateKnowledgeTagBatch godoc
|
||||
// @Summary 批量更新知识标签
|
||||
// @Description 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析
|
||||
// @Description 批量更新知识条目的标签。传 updates,或传 knowledge_ids 与 tag_ids。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析
|
||||
// @Tags 知识管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body object true "标签更新请求(updates 必填,kb_id 可选)"
|
||||
// @Param request body handler.KnowledgeTagBatchRequest true "标签更新请求"
|
||||
// @Success 200 {object} handler.SuccessResponse "更新成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge.set_tags","risk":"write","target":"knowledge_base.get","label":"name","items":{"param":"knowledge_ids","target":"knowledge.get","as":"knowledge_id","label":"title"}}
|
||||
// @x-agent-hint "Sets the same tags on up to 20 documents in one knowledge base, replacing the tags they have now. tag_ids come from knowledge_base.list_tags; an empty tag_ids clears every tag. It does not delete documents."
|
||||
// @Router /knowledge/tags [put]
|
||||
func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
@ -2683,12 +2739,16 @@ func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
|
|||
}
|
||||
ctx = types.WithExecutionTenant(ctx, tenantID)
|
||||
|
||||
var req knowledgeTagBatchRequest
|
||||
var req KnowledgeTagBatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse knowledge tag batch request", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := applyKnowledgeTagBatch(&req); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
// Resolve effective tenant and the authorized KB scope.
|
||||
var authorizedKBID string
|
||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestApplyKnowledgeTagBatch(t *testing.T) {
|
||||
req := &KnowledgeTagBatchRequest{
|
||||
KnowledgeIDs: []string{" k-1 ", "k-2"},
|
||||
TagIDs: []string{"t-1"},
|
||||
}
|
||||
require.NoError(t, applyKnowledgeTagBatch(req))
|
||||
assert.Equal(t, map[string][]string{"k-1": {"t-1"}, "k-2": {"t-1"}}, req.Updates)
|
||||
|
||||
cleared := &KnowledgeTagBatchRequest{KnowledgeIDs: []string{"k-1"}, TagIDs: []string{}}
|
||||
require.NoError(t, applyKnowledgeTagBatch(cleared))
|
||||
assert.Empty(t, cleared.Updates["k-1"])
|
||||
|
||||
kept := &KnowledgeTagBatchRequest{Updates: map[string][]string{"k-1": {"t-1"}}}
|
||||
require.NoError(t, applyKnowledgeTagBatch(kept))
|
||||
assert.Equal(t, map[string][]string{"k-1": {"t-1"}}, kept.Updates)
|
||||
|
||||
cases := []*KnowledgeTagBatchRequest{
|
||||
{},
|
||||
{KnowledgeIDs: []string{"k-1"}, Updates: map[string][]string{"k-2": nil}},
|
||||
{KnowledgeIDs: []string{"k-1"}},
|
||||
{KnowledgeIDs: []string{"k-1", "k-1"}, TagIDs: []string{}},
|
||||
{KnowledgeIDs: []string{" "}, TagIDs: []string{}},
|
||||
}
|
||||
for _, bad := range cases {
|
||||
require.Error(t, applyKnowledgeTagBatch(bad))
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
|
@ -460,6 +461,8 @@ func (h *KnowledgeBaseHandler) HybridSearch(c *gin.Context) {
|
|||
// @Failure 500 {object} errors.AppError "服务器错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.create","risk":"write","label_param":"name"}
|
||||
// @x-agent-hint "Creates a knowledge base owned by the user. Omit type for document. Omit indexing flags for vector and keyword search. Set embedding_model_id and summary_model_id from model.list. vector_store_id can be chosen only now. A field you leave out keeps its default."
|
||||
// @Router /knowledge-bases [post]
|
||||
func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
@ -467,12 +470,25 @@ func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) {
|
|||
logger.Info(ctx, "Start creating knowledge base")
|
||||
|
||||
// Parse request body
|
||||
var req types.KnowledgeBase
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
_ = c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
var req types.KnowledgeBase
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
_ = c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
_ = c.Error(apperrors.NewBadRequestError("name cannot be empty"))
|
||||
return
|
||||
}
|
||||
// A partial indexing_strategy must not turn the omitted pipelines off.
|
||||
// Missing flags keep the defaults: vector and keyword on, wiki and graph off.
|
||||
fillOmittedIndexingFlags(body, &req)
|
||||
if err := validateExtractConfig(req.ExtractConfig); err != nil {
|
||||
logger.Error(ctx, "Invalid extract configuration", err)
|
||||
c.Error(err)
|
||||
|
|
@ -839,13 +855,9 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
|
|||
c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
// The VLM model is a KB setting: like PUT /initialization/config, only the
|
||||
// owner workspace or an admin share may change it, not a share editor.
|
||||
if req.VLMConfig != nil {
|
||||
if _, err := kbSettingsAccess(c, currentKB); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if err := validateKnowledgeBaseSettingsUpdate(c, currentKB, req.Config, req.VLMConfig); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if req.Config != nil {
|
||||
probe := &types.KnowledgeBase{
|
||||
|
|
@ -878,8 +890,347 @@ func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base updated successfully, ID: %s",
|
||||
secutils.SanitizeForLog(id))
|
||||
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": buildKBResponse(kb, h.resolveKBStoreView(ctx, kb, callerTenantID), nil),
|
||||
})
|
||||
}
|
||||
|
||||
// validateKnowledgeBaseSettingsUpdate applies the same settings permissions to
|
||||
// PUT and PATCH. Shared editors may edit content, while model settings require
|
||||
// an admin share. Only the owner workspace may change the storage binding.
|
||||
func validateKnowledgeBaseSettingsUpdate(
|
||||
c *gin.Context, kb *types.KnowledgeBase, cfg *types.KnowledgeBaseConfig, vlm *types.VLMConfig,
|
||||
) error {
|
||||
settings := vlm != nil || cfg != nil && (cfg.EmbeddingModelID != nil || cfg.SummaryModelID != nil ||
|
||||
cfg.StorageBackendID != nil || cfg.ASRConfig != nil)
|
||||
if !settings {
|
||||
return nil
|
||||
}
|
||||
ownWorkspace, err := kbSettingsAccess(c, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ownWorkspace && cfg != nil && cfg.StorageBackendID != nil &&
|
||||
kbStorageBindingChanged(kb, *cfg.StorageBackendID, "") {
|
||||
return apperrors.NewForbiddenError("只有知识库所属空间可以修改存储配置")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PatchKnowledgeBaseRequest changes the settings it carries. A field left
|
||||
// out stays as it is, including fields inside chunking, indexing and models.
|
||||
type PatchKnowledgeBaseRequest struct {
|
||||
// New name. Omit to keep the current one.
|
||||
Name *string `json:"name" extensions:"x-agent"`
|
||||
// New description. Omit to keep it; an empty string clears it.
|
||||
Description *string `json:"description" extensions:"x-agent"`
|
||||
// Embedding model. Cannot change after the knowledge base has documents.
|
||||
EmbeddingModelID *string `json:"embedding_model_id" extensions:"x-agent=embedding_model_id"`
|
||||
// Summary model. model.list returns the ids.
|
||||
SummaryModelID *string `json:"summary_model_id" extensions:"x-agent=summary_model_id"`
|
||||
// Storage instance to bind. Omit to keep the current one.
|
||||
StorageBackendID *string `json:"storage_backend_id" extensions:"x-agent=storage_backend_id"`
|
||||
// Chunking settings. Only the fields present are changed.
|
||||
Chunking *types.ChunkingConfig `json:"chunking_config"`
|
||||
// Indexing pipelines. A flag left out stays as it is.
|
||||
Indexing *types.IndexingStrategy `json:"indexing_strategy"`
|
||||
// Image description settings.
|
||||
Image *types.ImageProcessingConfig `json:"image_processing_config"`
|
||||
// FAQ indexing. Only for an FAQ knowledge base.
|
||||
FAQ *types.FAQConfig `json:"faq_config"`
|
||||
// Wiki page settings.
|
||||
Wiki *types.WikiConfig `json:"wiki_config"`
|
||||
// Automatic tagging.
|
||||
AutoTag *types.AutoTagConfig `json:"auto_tag_config"`
|
||||
// AI description of the knowledge base.
|
||||
Profile *types.KnowledgeBaseProfileConfig `json:"profile_config"`
|
||||
// Image captions.
|
||||
VLM *types.VLMConfig `json:"vlm_config"`
|
||||
// Speech transcription.
|
||||
ASR *types.ASRConfig `json:"asr_config"`
|
||||
// Graph extraction. Node types stay in the knowledge base editor.
|
||||
Extract *types.ExtractConfig `json:"extract_config"`
|
||||
// Generated questions for each chunk.
|
||||
Questions *types.QuestionGenerationConfig `json:"question_generation_config"`
|
||||
}
|
||||
|
||||
// knowledgeBaseUpdate is the merged result of a partial knowledge base edit.
|
||||
type knowledgeBaseUpdate struct {
|
||||
Name string
|
||||
Description string
|
||||
Config *types.KnowledgeBaseConfig
|
||||
VLM *types.VLMConfig
|
||||
}
|
||||
|
||||
// applyKnowledgeBasePatch overlays the JSON sections that are present onto
|
||||
// the stored knowledge base. Omitted flags and nested fields stay.
|
||||
func applyKnowledgeBasePatch(
|
||||
kb *types.KnowledgeBase, patch PatchKnowledgeBaseRequest, sections map[string]json.RawMessage,
|
||||
) (knowledgeBaseUpdate, error) {
|
||||
out := knowledgeBaseUpdate{Name: kb.Name, Description: kb.Description}
|
||||
if patch.Name != nil {
|
||||
out.Name = strings.TrimSpace(*patch.Name)
|
||||
if out.Name == "" {
|
||||
return out, apperrors.NewBadRequestError("name cannot be empty")
|
||||
}
|
||||
}
|
||||
if patch.Description != nil {
|
||||
out.Description = *patch.Description
|
||||
}
|
||||
|
||||
cfg := &types.KnowledgeBaseConfig{ChunkingConfig: kb.ChunkingConfig}
|
||||
used := false
|
||||
merge := func(key string, dest any) error {
|
||||
raw, ok := sections[key]
|
||||
if !ok || len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(raw, dest); err != nil {
|
||||
return apperrors.NewBadRequestError("invalid " + key).WithDetails(err.Error())
|
||||
}
|
||||
used = true
|
||||
return nil
|
||||
}
|
||||
|
||||
chunking := kb.ChunkingConfig
|
||||
if err := merge("chunking_config", &chunking); err != nil {
|
||||
return out, err
|
||||
}
|
||||
cfg.ChunkingConfig = chunking
|
||||
|
||||
strategy := kb.IndexingStrategy
|
||||
before := len(sections["indexing_strategy"])
|
||||
if err := merge("indexing_strategy", &strategy); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if before > 0 && string(sections["indexing_strategy"]) != "null" {
|
||||
cfg.IndexingStrategy = &strategy
|
||||
}
|
||||
|
||||
image := kb.ImageProcessingConfig
|
||||
if err := merge("image_processing_config", &image); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["image_processing_config"]; ok && string(sections["image_processing_config"]) != "null" {
|
||||
cfg.ImageProcessingConfig = &image
|
||||
}
|
||||
|
||||
faq := types.FAQConfig{}
|
||||
if kb.FAQConfig != nil {
|
||||
faq = *kb.FAQConfig
|
||||
}
|
||||
if err := merge("faq_config", &faq); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["faq_config"]; ok && string(sections["faq_config"]) != "null" {
|
||||
cfg.FAQConfig = &faq
|
||||
}
|
||||
|
||||
wiki := types.WikiConfig{}
|
||||
if kb.WikiConfig != nil {
|
||||
wiki = *kb.WikiConfig
|
||||
}
|
||||
if err := merge("wiki_config", &wiki); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["wiki_config"]; ok && string(sections["wiki_config"]) != "null" {
|
||||
cfg.WikiConfig = &wiki
|
||||
}
|
||||
|
||||
autoTag := types.AutoTagConfig{}
|
||||
if kb.AutoTagConfig != nil {
|
||||
autoTag = *kb.AutoTagConfig
|
||||
}
|
||||
if err := merge("auto_tag_config", &autoTag); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["auto_tag_config"]; ok && string(sections["auto_tag_config"]) != "null" {
|
||||
cfg.AutoTagConfig = &autoTag
|
||||
}
|
||||
|
||||
profile := types.KnowledgeBaseProfileConfig{}
|
||||
if kb.ProfileConfig != nil {
|
||||
profile = *kb.ProfileConfig
|
||||
}
|
||||
if err := merge("profile_config", &profile); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["profile_config"]; ok && string(sections["profile_config"]) != "null" {
|
||||
cfg.ProfileConfig = &profile
|
||||
}
|
||||
|
||||
asr := kb.ASRConfig
|
||||
if err := merge("asr_config", &asr); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["asr_config"]; ok && string(sections["asr_config"]) != "null" {
|
||||
cfg.ASRConfig = &asr
|
||||
}
|
||||
|
||||
extract := types.ExtractConfig{}
|
||||
if kb.ExtractConfig != nil {
|
||||
extract = *kb.ExtractConfig
|
||||
}
|
||||
if err := merge("extract_config", &extract); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["extract_config"]; ok && string(sections["extract_config"]) != "null" {
|
||||
if err := validateExtractConfig(&extract); err != nil {
|
||||
return out, err
|
||||
}
|
||||
cfg.ExtractConfig = &extract
|
||||
}
|
||||
|
||||
questions := types.QuestionGenerationConfig{}
|
||||
if kb.QuestionGenerationConfig != nil {
|
||||
questions = *kb.QuestionGenerationConfig
|
||||
}
|
||||
if err := merge("question_generation_config", &questions); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["question_generation_config"]; ok && string(sections["question_generation_config"]) != "null" {
|
||||
cfg.QuestionGenerationConfig = &questions
|
||||
}
|
||||
|
||||
vlm := kb.VLMConfig
|
||||
if err := merge("vlm_config", &vlm); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if _, ok := sections["vlm_config"]; ok && string(sections["vlm_config"]) != "null" {
|
||||
out.VLM = &vlm
|
||||
}
|
||||
|
||||
if patch.EmbeddingModelID != nil {
|
||||
cfg.EmbeddingModelID = patch.EmbeddingModelID
|
||||
used = true
|
||||
}
|
||||
if patch.SummaryModelID != nil {
|
||||
cfg.SummaryModelID = patch.SummaryModelID
|
||||
used = true
|
||||
}
|
||||
if patch.StorageBackendID != nil {
|
||||
cfg.StorageBackendID = patch.StorageBackendID
|
||||
used = true
|
||||
}
|
||||
if used {
|
||||
out.Config = cfg
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fillOmittedIndexingFlags keeps DefaultIndexingStrategy for flags the
|
||||
// create body did not mention.
|
||||
func fillOmittedIndexingFlags(raw []byte, kb *types.KnowledgeBase) {
|
||||
var body map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
return
|
||||
}
|
||||
strategyRaw, ok := body["indexing_strategy"]
|
||||
if !ok || len(strategyRaw) == 0 || string(strategyRaw) == "null" {
|
||||
return
|
||||
}
|
||||
var present map[string]json.RawMessage
|
||||
if err := json.Unmarshal(strategyRaw, &present); err != nil {
|
||||
return
|
||||
}
|
||||
defaults := types.DefaultIndexingStrategy()
|
||||
if _, ok := present["vector_enabled"]; !ok {
|
||||
kb.IndexingStrategy.VectorEnabled = defaults.VectorEnabled
|
||||
}
|
||||
if _, ok := present["keyword_enabled"]; !ok {
|
||||
kb.IndexingStrategy.KeywordEnabled = defaults.KeywordEnabled
|
||||
}
|
||||
if _, ok := present["wiki_enabled"]; !ok {
|
||||
kb.IndexingStrategy.WikiEnabled = defaults.WikiEnabled
|
||||
}
|
||||
if _, ok := present["graph_enabled"]; !ok {
|
||||
kb.IndexingStrategy.GraphEnabled = defaults.GraphEnabled
|
||||
}
|
||||
}
|
||||
|
||||
// PatchKnowledgeBase godoc
|
||||
// @Summary 部分更新知识库
|
||||
// @Description 修改请求里出现的设置。未出现的字段保持不变,包括分块、索引和模型里没写到的项。
|
||||
// @Tags 知识库
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
|
||||
// @Param request body handler.PatchKnowledgeBaseRequest true "要修改的字段"
|
||||
// @Success 200 {object} handler.DataResponse{data=handler.KnowledgeBaseView} "更新后的知识库"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "无权限"
|
||||
// @Failure 404 {object} errors.AppError "知识库不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.update","risk":"write","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Changes the settings you send; a field left out is kept, including one indexing flag or one chunking field. Model ids come from model.list. embedding_model_id cannot change after documents exist. vector_store_id cannot be changed. Graph node types stay in the knowledge base editor."
|
||||
// @Router /knowledge-bases/{id} [patch]
|
||||
func (h *KnowledgeBaseHandler) PatchKnowledgeBase(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
currentKB, id, _, permission, err := h.validateAndGetKnowledgeBase(c)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor {
|
||||
_ = c.Error(apperrors.NewForbiddenError("No permission to update knowledge base"))
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
_ = c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
var patch PatchKnowledgeBaseRequest
|
||||
if err := json.Unmarshal(body, &patch); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
_ = c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
var sections map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, §ions); err != nil {
|
||||
_ = c.Error(apperrors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
update, err := applyKnowledgeBasePatch(currentKB, patch, sections)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if err := validateKnowledgeBaseSettingsUpdate(c, currentKB, update.Config, update.VLM); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
if update.Config != nil || update.VLM != nil {
|
||||
probe := &types.KnowledgeBase{ChunkingConfig: currentKB.ChunkingConfig, VLMConfig: currentKB.VLMConfig}
|
||||
if update.Config != nil {
|
||||
probe.ChunkingConfig = update.Config.ChunkingConfig
|
||||
probe.WikiConfig = update.Config.WikiConfig
|
||||
probe.ProfileConfig = update.Config.ProfileConfig
|
||||
if update.Config.ImageProcessingConfig != nil {
|
||||
probe.ImageProcessingConfig = *update.Config.ImageProcessingConfig
|
||||
}
|
||||
}
|
||||
if update.VLM != nil {
|
||||
probe.VLMConfig = *update.VLM
|
||||
}
|
||||
if err := validateKnowledgeBasePromptInstructions(probe); err != nil {
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
kb, err := h.service.UpdateKnowledgeBase(ctx, id, update.Name, update.Description, update.Config, update.VLM)
|
||||
if err != nil {
|
||||
if appErr, ok := apperrors.IsAppError(err); ok {
|
||||
_ = c.Error(appErr)
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
_ = c.Error(apperrors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
|
|
@ -945,13 +1296,15 @@ const knowledgeBaseProfileRequestTimeout = 2 * time.Minute
|
|||
// @Tags 知识库
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
|
||||
// @Success 200 {object} handler.MessageResponse "删除成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "仅所有者可删除"
|
||||
// @Failure 404 {object} errors.AppError "知识库不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.delete","risk":"destructive","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Deletes the knowledge base and every document in it. Cannot be undone. Only the owner can delete it."
|
||||
// @Router /knowledge-bases/{id} [delete]
|
||||
func (h *KnowledgeBaseHandler) DeleteKnowledgeBase(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestApplyKnowledgeBasePatchKeepsOmittedFields(t *testing.T) {
|
||||
name := "产品文档"
|
||||
kb := &types.KnowledgeBase{
|
||||
Name: "旧名称",
|
||||
Description: "旧描述",
|
||||
ChunkingConfig: types.ChunkingConfig{
|
||||
ChunkSize: 512,
|
||||
ChunkOverlap: 50,
|
||||
},
|
||||
IndexingStrategy: types.IndexingStrategy{VectorEnabled: true, KeywordEnabled: true},
|
||||
}
|
||||
|
||||
got, err := applyKnowledgeBasePatch(kb, PatchKnowledgeBaseRequest{Name: &name}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "产品文档", got.Name)
|
||||
assert.Equal(t, "旧描述", got.Description, "an omitted description stays")
|
||||
assert.Nil(t, got.Config)
|
||||
|
||||
cleared := ""
|
||||
got, err = applyKnowledgeBasePatch(kb, PatchKnowledgeBaseRequest{Description: &cleared}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "旧名称", got.Name)
|
||||
assert.Empty(t, got.Description)
|
||||
|
||||
blank := " "
|
||||
_, err = applyKnowledgeBasePatch(kb, PatchKnowledgeBaseRequest{Name: &blank}, nil)
|
||||
require.Error(t, err)
|
||||
|
||||
got, err = applyKnowledgeBasePatch(kb, PatchKnowledgeBaseRequest{}, map[string]json.RawMessage{
|
||||
"indexing_strategy": json.RawMessage(`{"wiki_enabled":true}`),
|
||||
"chunking_config": json.RawMessage(`{"chunk_size":800}`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.Config)
|
||||
require.NotNil(t, got.Config.IndexingStrategy)
|
||||
assert.True(t, got.Config.IndexingStrategy.VectorEnabled, "an omitted indexing flag stays on")
|
||||
assert.True(t, got.Config.IndexingStrategy.KeywordEnabled)
|
||||
assert.True(t, got.Config.IndexingStrategy.WikiEnabled)
|
||||
assert.False(t, got.Config.IndexingStrategy.GraphEnabled)
|
||||
assert.Equal(t, 800, got.Config.ChunkingConfig.ChunkSize)
|
||||
assert.Equal(t, 50, got.Config.ChunkingConfig.ChunkOverlap, "an omitted chunking field stays")
|
||||
}
|
||||
|
||||
func TestFillOmittedIndexingFlagsKeepsDefaults(t *testing.T) {
|
||||
raw := []byte(`{"name":"产品文档","indexing_strategy":{"wiki_enabled":true}}`)
|
||||
kb := &types.KnowledgeBase{}
|
||||
require.NoError(t, json.Unmarshal(raw, kb))
|
||||
fillOmittedIndexingFlags(raw, kb)
|
||||
assert.True(t, kb.IndexingStrategy.VectorEnabled)
|
||||
assert.True(t, kb.IndexingStrategy.KeywordEnabled)
|
||||
assert.True(t, kb.IndexingStrategy.WikiEnabled)
|
||||
assert.False(t, kb.IndexingStrategy.GraphEnabled)
|
||||
|
||||
raw = []byte(`{"indexing_strategy":{"vector_enabled":false,"keyword_enabled":false,` +
|
||||
`"wiki_enabled":false,"graph_enabled":true}}`)
|
||||
explicit := &types.KnowledgeBase{}
|
||||
require.NoError(t, json.Unmarshal(raw, explicit))
|
||||
fillOmittedIndexingFlags(raw, explicit)
|
||||
assert.False(t, explicit.IndexingStrategy.VectorEnabled)
|
||||
assert.True(t, explicit.IndexingStrategy.GraphEnabled)
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestKnowledgeBaseUpdateSettingsAccess(t *testing.T) {
|
||||
for _, method := range []string{http.MethodPut, http.MethodPatch} {
|
||||
for _, caller := range []struct {
|
||||
name string
|
||||
owner uint64
|
||||
permission types.OrgMemberRole
|
||||
}{
|
||||
{"owner", 1, types.OrgRoleAdmin},
|
||||
{"share admin", 2, types.OrgRoleAdmin},
|
||||
{"share editor", 2, types.OrgRoleEditor},
|
||||
} {
|
||||
for _, setting := range []struct {
|
||||
field string
|
||||
value any
|
||||
rebind bool
|
||||
}{
|
||||
{"name", "renamed", false},
|
||||
{"embedding_model_id", "embedding", false},
|
||||
{"summary_model_id", "summary", false},
|
||||
{"asr_config", map[string]any{"enabled": false}, false},
|
||||
{"vlm_config", map[string]any{"enabled": false}, false},
|
||||
{"storage_backend_id", "receiver-store", true},
|
||||
{"storage_backend_id", "owner-store", false},
|
||||
} {
|
||||
name := method + "/" + caller.name + "/" + setting.field
|
||||
if setting.rebind {
|
||||
name += "/rebind"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
backend := "owner-store"
|
||||
svc := &vlmUpdateKBService{kb: &types.KnowledgeBase{
|
||||
ID: "kb-1", TenantID: caller.owner, StorageBackendID: &backend,
|
||||
}}
|
||||
shares := &vlmUpdateShareStub{permission: caller.permission}
|
||||
h := &KnowledgeBaseHandler{service: svc, kbShareService: shares}
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(1))
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Set(types.TenantIDContextKey.String(), uint64(1))
|
||||
c.Next()
|
||||
})
|
||||
enabled := true
|
||||
handle := h.UpdateKnowledgeBase
|
||||
if method == http.MethodPatch {
|
||||
handle = h.PatchKnowledgeBase
|
||||
}
|
||||
r.Handle(method, "/:id", middleware.RequireKBAccess(
|
||||
middleware.KBIDFromParam("id"), types.OrgRoleEditor, svc, shares, nil,
|
||||
&config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}},
|
||||
), handle)
|
||||
body := map[string]any{"name": "renamed"}
|
||||
if method == http.MethodPut && setting.field != "name" && setting.field != "vlm_config" {
|
||||
body["config"] = map[string]any{setting.field: setting.value}
|
||||
} else {
|
||||
body[setting.field] = setting.value
|
||||
}
|
||||
encoded, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
req := httptest.NewRequest(method, "/kb-1", strings.NewReader(string(encoded)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
want := http.StatusOK
|
||||
if caller.owner != 1 && setting.field != "name" &&
|
||||
(caller.permission != types.OrgRoleAdmin || setting.rebind) {
|
||||
want = http.StatusForbidden
|
||||
}
|
||||
require.Equal(t, want, w.Code, w.Body.String())
|
||||
require.Equal(t, want == http.StatusOK, svc.updated)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -112,8 +112,10 @@ func (h *TagHandler) ListTags(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
type createTagRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
// CreateTagRequest is the body of POST /knowledge-bases/{id}/tags.
|
||||
type CreateTagRequest struct {
|
||||
// Tag name, unique in this knowledge base
|
||||
Name string `json:"name" binding:"required" extensions:"x-agent"`
|
||||
Color string `json:"color"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
|
@ -124,18 +126,20 @@ type createTagRequest struct {
|
|||
// @Tags 标签管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param request body object{name=string,color=string,sort_order=int} true "标签信息"
|
||||
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
|
||||
// @Param request body handler.CreateTagRequest true "标签信息"
|
||||
// @Success 200 {object} handler.DataResponse{data=types.KnowledgeTag} "创建的标签"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.create_tag","risk":"write","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Creates a tag in the knowledge base. Pass the returned tag id to knowledge.set_tags."
|
||||
// @Router /knowledge-bases/{id}/tags [post]
|
||||
func (h *TagHandler) CreateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
var req createTagRequest
|
||||
var req CreateTagRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind create tag payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
|
|
@ -158,8 +162,10 @@ func (h *TagHandler) CreateTag(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
type updateTagRequest struct {
|
||||
Name *string `json:"name"`
|
||||
// UpdateTagRequest is the body of PUT /knowledge-bases/{id}/tags/{tag_id}.
|
||||
type UpdateTagRequest struct {
|
||||
// New name. Omit to keep the current one.
|
||||
Name *string `json:"name" extensions:"x-agent"`
|
||||
Color *string `json:"color"`
|
||||
SortOrder *int `json:"sort_order"`
|
||||
}
|
||||
|
|
@ -170,13 +176,15 @@ type updateTagRequest struct {
|
|||
// @Tags 标签管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)"
|
||||
// @Param request body object true "标签更新信息"
|
||||
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)" extensions(x-agent=tag_id)
|
||||
// @Param request body handler.UpdateTagRequest true "标签更新信息"
|
||||
// @Success 200 {object} handler.DataResponse{data=types.KnowledgeTag} "更新后的标签"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.update_tag","risk":"write","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Renames a tag. tag_id comes from knowledge_base.list_tags. A field left out is kept."
|
||||
// @Router /knowledge-bases/{id}/tags/{tag_id} [put]
|
||||
func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
@ -187,7 +195,7 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
var req updateTagRequest
|
||||
var req UpdateTagRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind update tag payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
|
|
@ -215,8 +223,8 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
|||
// @Tags 标签管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)"
|
||||
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)" extensions(x-agent=tag_id)
|
||||
// @Param force query bool false "强制删除"
|
||||
// @Param content_only query bool false "仅删除内容,保留标签"
|
||||
// @Param body body DeleteTagRequest false "删除选项"
|
||||
|
|
@ -224,6 +232,8 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
|||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @x-agent {"id":"knowledge_base.delete_tag","risk":"destructive","target":"knowledge_base.get","label":"name"}
|
||||
// @x-agent-hint "Deletes a tag that no document uses. If documents still use it, this fails; take the tag off them with knowledge.set_tags first. Documents are not deleted."
|
||||
// @Router /knowledge-bases/{id}/tags/{tag_id} [delete]
|
||||
func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
|
|
|||
|
|
@ -229,6 +229,7 @@ func TestKnowledgeBaseManagementRoutesDeclareManageKBsCapability(t *testing.T) {
|
|||
path string
|
||||
}{
|
||||
{http.MethodPut, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodPatch, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodDelete, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodPost, "/api/v1/initialization/initialize/:kbId"},
|
||||
{http.MethodPut, "/api/v1/initialization/config/:kbId"},
|
||||
|
|
|
|||
|
|
@ -233,6 +233,7 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
|||
// 以调用者「自身」租户(c.Keys,未被 KBAccess 改写)校验 kb.TenantID,
|
||||
// 把删除锁死为「所有者租户 + Admin」,共享 editor 无法删除源 KB。
|
||||
kbManagement.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
|
||||
kbManagement.PATCH("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.PatchKnowledgeBase)
|
||||
// 立即重新生成知识库 AI 描述 — 与更新知识库同档鉴权;同步执行一次小模型调用。
|
||||
kbManagement.POST("/:id/profile/generate", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"),
|
||||
handler.GenerateKnowledgeBaseProfile)
|
||||
|
|
|
|||
|
|
@ -330,9 +330,9 @@ type ManualKnowledgePayload struct {
|
|||
Title string `json:"title" extensions:"x-agent"`
|
||||
// Markdown content. The assistant may send a full document; the API limit
|
||||
// is 200000 runes, and x-agent-max-bytes covers that in UTF-8.
|
||||
Content string `json:"content" extensions:"x-agent,x-agent-max-bytes=800000"`
|
||||
Content string `json:"content" extensions:"x-agent,x-agent-required,x-agent-max-bytes=800000"`
|
||||
// draft keeps the document out of search; publish indexes it.
|
||||
Status string `json:"status" enums:"draft,publish" extensions:"x-agent"`
|
||||
Status string `json:"status" enums:"draft,publish" extensions:"x-agent,x-agent-required"`
|
||||
TagIDs []string `json:"tag_ids"`
|
||||
Channel string `json:"channel"`
|
||||
ProcessConfig *KnowledgeProcessOverrides `json:"process_config,omitempty"`
|
||||
|
|
|
|||
|
|
@ -58,11 +58,11 @@ const (
|
|||
// KnowledgeBase represents a knowledge base entity
|
||||
type KnowledgeBase struct {
|
||||
// Unique identifier of the knowledge base
|
||||
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey" extensions:"x-agent=knowledge_base_id"`
|
||||
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey" extensions:"x-agent=knowledge_base_id,x-agent-response"`
|
||||
// Name of the knowledge base
|
||||
Name string `yaml:"name" json:"name" extensions:"x-agent"`
|
||||
// Type of the knowledge base (document, faq, etc.)
|
||||
Type string `yaml:"type" json:"type" gorm:"type:varchar(32);default:'document'" extensions:"x-agent"`
|
||||
Name string `yaml:"name" json:"name" binding:"required" extensions:"x-agent,x-agent-required"`
|
||||
// Type of the knowledge base: document, faq or wiki. Empty means document.
|
||||
Type string `yaml:"type" json:"type" gorm:"type:varchar(32);default:'document'" enums:"document,faq,wiki" extensions:"x-agent"`
|
||||
// Whether this knowledge base is temporary (ephemeral) and should be hidden from UI
|
||||
IsTemporary bool `yaml:"is_temporary" json:"is_temporary" gorm:"default:false"`
|
||||
// Description of the knowledge base
|
||||
|
|
@ -76,22 +76,23 @@ type KnowledgeBase struct {
|
|||
// RBAC migration backfilled the column to the workspace Owner.
|
||||
CreatorID string `yaml:"creator_id" json:"creator_id" gorm:"type:varchar(36);index"`
|
||||
// Chunking configuration
|
||||
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"`
|
||||
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// Image processing configuration
|
||||
ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config" gorm:"type:json"`
|
||||
// ID of the embedding model
|
||||
EmbeddingModelID string `yaml:"embedding_model_id" json:"embedding_model_id"`
|
||||
// Summary model ID
|
||||
SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id"`
|
||||
ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config" gorm:"type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// ID of the embedding model. model.list returns the ids. Cannot change after the knowledge base has documents.
|
||||
EmbeddingModelID string `yaml:"embedding_model_id" json:"embedding_model_id" extensions:"x-agent=embedding_model_id"`
|
||||
// Summary model ID. model.list returns the ids. Used for summaries, and as
|
||||
// the default for auto-tagging and the AI description.
|
||||
SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id" extensions:"x-agent=summary_model_id"`
|
||||
// VLM config
|
||||
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"`
|
||||
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// ASR config (Automatic Speech Recognition)
|
||||
ASRConfig ASRConfig `yaml:"asr_config" json:"asr_config" gorm:"type:json"`
|
||||
ASRConfig ASRConfig `yaml:"asr_config" json:"asr_config" gorm:"type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// Storage provider config (new): only stores provider selection; credentials from workspace StorageEngineConfig
|
||||
StorageProviderConfig *StorageProviderConfig `yaml:"storage_provider_config" json:"storage_provider_config" gorm:"column:storage_provider_config;type:jsonb"`
|
||||
// StorageBackendID binds this KB to one concrete storage instance. The
|
||||
// legacy provider field remains readable during migration only.
|
||||
StorageBackendID *string `yaml:"storage_backend_id" json:"storage_backend_id,omitempty" gorm:"column:storage_backend_id;type:varchar(36);default:null"`
|
||||
StorageBackendID *string `yaml:"storage_backend_id" json:"storage_backend_id,omitempty" gorm:"column:storage_backend_id;type:varchar(36);default:null" extensions:"x-agent=storage_backend_id"`
|
||||
// Deprecated: legacy COS config column. Kept for backward compatibility with old data.
|
||||
StorageConfig StorageConfig `yaml:"-" json:"storage_config" gorm:"column:cos_config;type:json"`
|
||||
// VectorStoreID references the VectorStore this knowledge base is bound to.
|
||||
|
|
@ -100,27 +101,27 @@ type KnowledgeBase struct {
|
|||
// This field is set once at creation time and must not be modified afterwards;
|
||||
// enforcement lives at the GORM layer (`<-:create`) plus the service-layer
|
||||
// KB update path, which omits this field from its update DTO.
|
||||
VectorStoreID *string `yaml:"vector_store_id" json:"vector_store_id,omitempty" gorm:"column:vector_store_id;type:varchar(36);<-:create"`
|
||||
VectorStoreID *string `yaml:"vector_store_id" json:"vector_store_id,omitempty" gorm:"column:vector_store_id;type:varchar(36);<-:create" extensions:"x-agent=vector_store_id"`
|
||||
// Extract config
|
||||
ExtractConfig *ExtractConfig `yaml:"extract_config" json:"extract_config" gorm:"column:extract_config;type:json"`
|
||||
ExtractConfig *ExtractConfig `yaml:"extract_config" json:"extract_config" gorm:"column:extract_config;type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// FAQConfig stores FAQ specific configuration such as indexing strategy
|
||||
FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config" gorm:"column:faq_config;type:json"`
|
||||
FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config" gorm:"column:faq_config;type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// QuestionGenerationConfig stores question generation configuration for document knowledge bases
|
||||
QuestionGenerationConfig *QuestionGenerationConfig `yaml:"question_generation_config" json:"question_generation_config" gorm:"column:question_generation_config;type:json"`
|
||||
QuestionGenerationConfig *QuestionGenerationConfig `yaml:"question_generation_config" json:"question_generation_config" gorm:"column:question_generation_config;type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// AutoTagConfig controls asynchronous association of existing tags after parsing.
|
||||
AutoTagConfig *AutoTagConfig `yaml:"auto_tag_config" json:"auto_tag_config" gorm:"type:json"`
|
||||
AutoTagConfig *AutoTagConfig `yaml:"auto_tag_config" json:"auto_tag_config" gorm:"type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// ProfileConfig controls automatic generation of the knowledge-base
|
||||
// description from per-document profiles (document knowledge bases only).
|
||||
ProfileConfig *KnowledgeBaseProfileConfig `yaml:"profile_config" json:"profile_config" gorm:"column:profile_config;type:json"` //nolint:lll // one-line struct tag
|
||||
ProfileConfig *KnowledgeBaseProfileConfig `yaml:"profile_config" json:"profile_config" gorm:"column:profile_config;type:json" extensions:"x-agent,x-agent-detail"` //nolint:lll // one-line struct tag
|
||||
// GeneratedProfile is the machine-generated description: a gist, merged
|
||||
// topics, typical questions and the aggregate snapshot they came from. It
|
||||
// never overwrites the user-authored Description; both are shown to agents.
|
||||
GeneratedProfile *KnowledgeBaseProfile `yaml:"generated_profile" json:"generated_profile,omitempty" gorm:"column:generated_profile;type:json"` //nolint:lll // one-line struct tag
|
||||
// WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases)
|
||||
WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config" gorm:"column:wiki_config;type:json"`
|
||||
WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config" gorm:"column:wiki_config;type:json" extensions:"x-agent,x-agent-detail"`
|
||||
// IndexingStrategy controls which indexing pipelines are active for this knowledge base.
|
||||
// Pipelines: vector search, keyword search, wiki generation, knowledge graph extraction.
|
||||
IndexingStrategy IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy" gorm:"column:indexing_strategy;type:json" extensions:"x-agent"`
|
||||
IndexingStrategy IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy" gorm:"column:indexing_strategy;type:json" extensions:"x-agent,x-agent-response"`
|
||||
// IsPinned and PinnedAt are computed per-caller from user_kb_pins
|
||||
// (see migration 000050). They used to be stored on the row itself,
|
||||
// which made pinning a workspace-wide ordering decision gated behind
|
||||
|
|
@ -136,17 +137,17 @@ type KnowledgeBase struct {
|
|||
// Creation time of the knowledge base
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
// Last updated time of the knowledge base
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at" extensions:"x-agent"`
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at" extensions:"x-agent,x-agent-response"`
|
||||
// Deletion time of the knowledge base
|
||||
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
|
||||
// Knowledge count (not stored in database, calculated on query)
|
||||
KnowledgeCount int64 `yaml:"knowledge_count" json:"knowledge_count" gorm:"-" extensions:"x-agent"`
|
||||
KnowledgeCount int64 `yaml:"knowledge_count" json:"knowledge_count" gorm:"-" extensions:"x-agent,x-agent-response"`
|
||||
// Chunk count (not stored in database, calculated on query)
|
||||
ChunkCount int64 `yaml:"chunk_count" json:"chunk_count" gorm:"-" extensions:"x-agent"`
|
||||
ChunkCount int64 `yaml:"chunk_count" json:"chunk_count" gorm:"-" extensions:"x-agent,x-agent-response"`
|
||||
// IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases)
|
||||
IsProcessing bool `yaml:"is_processing" json:"is_processing" gorm:"-" extensions:"x-agent"`
|
||||
IsProcessing bool `yaml:"is_processing" json:"is_processing" gorm:"-" extensions:"x-agent,x-agent-response"`
|
||||
// ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)
|
||||
ProcessingCount int64 `yaml:"processing_count" json:"processing_count" gorm:"-" extensions:"x-agent"`
|
||||
ProcessingCount int64 `yaml:"processing_count" json:"processing_count" gorm:"-" extensions:"x-agent,x-agent-response"`
|
||||
// ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)
|
||||
ShareCount int64 `yaml:"share_count" json:"share_count" gorm:"-"`
|
||||
// CreatorName 是 CreatorID 对应用户的展示名(username / email 等),
|
||||
|
|
@ -180,6 +181,19 @@ type KnowledgeBaseConfig struct {
|
|||
// IndexingStrategy controls which indexing pipelines are active.
|
||||
// nil means "no change" when updating (preserves existing strategy).
|
||||
IndexingStrategy *IndexingStrategy `yaml:"indexing_strategy" json:"indexing_strategy"`
|
||||
// EmbeddingModelID changes the embedding model. nil means no change.
|
||||
// A knowledge base that already has documents cannot switch models.
|
||||
EmbeddingModelID *string `json:"embedding_model_id,omitempty"`
|
||||
// SummaryModelID changes the summary model. nil means no change.
|
||||
SummaryModelID *string `json:"summary_model_id,omitempty"`
|
||||
// StorageBackendID rebinds file storage. nil means no change.
|
||||
StorageBackendID *string `json:"storage_backend_id,omitempty"`
|
||||
// ASRConfig replaces speech-recognition settings when set. nil means no change.
|
||||
ASRConfig *ASRConfig `json:"asr_config,omitempty"`
|
||||
// ExtractConfig replaces graph extraction settings when set. nil means no change.
|
||||
ExtractConfig *ExtractConfig `json:"extract_config,omitempty"`
|
||||
// QuestionGenerationConfig replaces generated-question settings when set. nil means no change.
|
||||
QuestionGenerationConfig *QuestionGenerationConfig `json:"question_generation_config,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
|
|
@ -193,14 +207,14 @@ const (
|
|||
// opt-in so upgrading an existing deployment does not add model calls or alter
|
||||
// document tags unexpectedly.
|
||||
type AutoTagConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty"`
|
||||
MaxTags int `yaml:"max_tags,omitempty" json:"max_tags,omitempty"`
|
||||
// SkipIfTagged leaves documents that already carry tags untouched, so a
|
||||
// deliberate manual classification is not diluted by model guesses. It is
|
||||
// a pointer because the default is true: rows written before this field
|
||||
// existed decode to nil and must not silently flip to "always append".
|
||||
SkipIfTagged *bool `yaml:"skip_if_tagged,omitempty" json:"skip_if_tagged,omitempty"`
|
||||
// Enabled turns automatic tagging on. The model picks from tags that already exist.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=auto_tag_enabled"`
|
||||
// ModelID overrides the summary model. Empty uses summary_model_id.
|
||||
ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty" extensions:"x-agent=auto_tag_model_id"`
|
||||
// MaxTags is how many tags one document may receive, from 1 to 10.
|
||||
MaxTags int `yaml:"max_tags,omitempty" json:"max_tags,omitempty" minimum:"1" maximum:"10" extensions:"x-agent=auto_tag_max_tags"`
|
||||
// SkipIfTagged leaves a document alone when it already has tags. Empty means yes.
|
||||
SkipIfTagged *bool `yaml:"skip_if_tagged,omitempty" json:"skip_if_tagged,omitempty" extensions:"x-agent=auto_tag_skip_if_tagged"`
|
||||
}
|
||||
|
||||
// ShouldSkipIfTagged reports whether documents with existing tags are left
|
||||
|
|
@ -259,43 +273,36 @@ type ParserEngineRule struct {
|
|||
|
||||
// ChunkingConfig represents the document splitting configuration
|
||||
type ChunkingConfig struct {
|
||||
// Chunk size
|
||||
ChunkSize int `yaml:"chunk_size" json:"chunk_size"`
|
||||
// Chunk overlap
|
||||
ChunkOverlap int `yaml:"chunk_overlap" json:"chunk_overlap"`
|
||||
// Separators
|
||||
Separators []string `yaml:"separators" json:"separators"`
|
||||
// Chunk size in characters. Empty on create uses the server default.
|
||||
ChunkSize int `yaml:"chunk_size" json:"chunk_size" minimum:"100" maximum:"10000" extensions:"x-agent"`
|
||||
// Chunk overlap in characters.
|
||||
ChunkOverlap int `yaml:"chunk_overlap" json:"chunk_overlap" minimum:"0" maximum:"5000" extensions:"x-agent"`
|
||||
// Separators, in the order they are tried.
|
||||
Separators []string `yaml:"separators" json:"separators" extensions:"x-agent,x-agent-maximum=20"`
|
||||
// ParserEngineRules configures which parser engine to use for each file type.
|
||||
// When empty, DefaultParserEngine is used (builtin/simple routing, except
|
||||
// types that only a specific engine can parse: ppt/pptx fall back to
|
||||
// markitdown). A linked anydoc binding is preferred for every type it
|
||||
// converts.
|
||||
ParserEngineRules []ParserEngineRule `yaml:"parser_engine_rules,omitempty" json:"parser_engine_rules,omitempty"`
|
||||
// EnableParentChild enables two-level parent-child chunking strategy.
|
||||
// When enabled, large parent chunks provide context while small child chunks
|
||||
// are used for vector matching. Retrieval matches on child but returns parent content.
|
||||
EnableParentChild bool `yaml:"enable_parent_child,omitempty" json:"enable_parent_child,omitempty"`
|
||||
// EnableParentChild splits into large parent chunks and small child chunks.
|
||||
// Search matches a child and returns its parent.
|
||||
EnableParentChild bool `yaml:"enable_parent_child,omitempty" json:"enable_parent_child,omitempty" extensions:"x-agent"`
|
||||
// ParentChunkSize is the size of parent chunks (default: 4096).
|
||||
// Only used when EnableParentChild is true.
|
||||
ParentChunkSize int `yaml:"parent_chunk_size,omitempty" json:"parent_chunk_size,omitempty"`
|
||||
ParentChunkSize int `yaml:"parent_chunk_size,omitempty" json:"parent_chunk_size,omitempty" minimum:"1" maximum:"20000" extensions:"x-agent"`
|
||||
// ChildChunkSize is the size of child chunks used for embedding (default: 384).
|
||||
// Only used when EnableParentChild is true.
|
||||
ChildChunkSize int `yaml:"child_chunk_size,omitempty" json:"child_chunk_size,omitempty"`
|
||||
// Strategy selects the adaptive chunking tier. Empty / "legacy" preserves
|
||||
// the historical recursive splitter; "auto" lets a profiler pick between
|
||||
// heading-aware, heuristic and recursive tiers; "heading" / "heuristic" /
|
||||
// "recursive" pin the tier explicitly.
|
||||
Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`
|
||||
// TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize
|
||||
// as a character count.
|
||||
TokenLimit int `yaml:"token_limit,omitempty" json:"token_limit,omitempty"`
|
||||
// Languages hints the heuristic patterns. Empty = auto-detect from content.
|
||||
// Examples: ["de"], ["en", "zh"].
|
||||
Languages []string `yaml:"languages,omitempty" json:"languages,omitempty"`
|
||||
// TableMetadataInstructions contains optional business guidance used when
|
||||
// generating searchable summaries for CSV/Excel tables. The system-owned
|
||||
// output contract remains fixed; these instructions only add domain context.
|
||||
TableMetadataInstructions string `yaml:"table_metadata_instructions,omitempty" json:"table_metadata_instructions,omitempty"`
|
||||
ChildChunkSize int `yaml:"child_chunk_size,omitempty" json:"child_chunk_size,omitempty" minimum:"1" maximum:"10000" extensions:"x-agent"`
|
||||
// Strategy selects how documents are split: auto, heading, heuristic,
|
||||
// recursive or legacy. Empty keeps the server default.
|
||||
Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty" enums:"auto,heading,heuristic,recursive,legacy" extensions:"x-agent"`
|
||||
// TokenLimit caps chunk size in approximate tokens. 0 uses ChunkSize as a character count.
|
||||
TokenLimit int `yaml:"token_limit,omitempty" json:"token_limit,omitempty" minimum:"0" maximum:"100000" extensions:"x-agent"`
|
||||
// Languages hints the splitter, for example de or zh. Empty detects the language from the document.
|
||||
Languages []string `yaml:"languages,omitempty" json:"languages,omitempty" extensions:"x-agent,x-agent-maximum=20"`
|
||||
// TableMetadataInstructions is extra guidance for CSV and Excel summaries. The output format stays fixed.
|
||||
TableMetadataInstructions string `yaml:"table_metadata_instructions,omitempty" json:"table_metadata_instructions,omitempty" extensions:"x-agent,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
}
|
||||
|
||||
// defaultParserEngineByType maps file types the builtin/simple engines cannot
|
||||
|
|
@ -538,8 +545,8 @@ func ParseProviderScheme(filePath string) string {
|
|||
|
||||
// ImageProcessingConfig represents the image processing configuration
|
||||
type ImageProcessingConfig struct {
|
||||
// Model ID
|
||||
ModelID string `yaml:"model_id" json:"model_id"`
|
||||
// Model ID used when describing images. Empty uses the knowledge base's caption model.
|
||||
ModelID string `yaml:"model_id" json:"model_id" extensions:"x-agent=image_model_id"`
|
||||
// ImageActions overrides the built-in attribute→work table (see
|
||||
// DefaultImageActions). A nil value keeps the conservative default: run OCR
|
||||
// for block text, data visuals, and unobserved images.
|
||||
|
|
@ -552,14 +559,14 @@ type ImageProcessingConfig struct {
|
|||
// the attribute policy decides whether OCR runs for it. A single upload can
|
||||
// override it per document through
|
||||
// KnowledgeProcessOverrides.ImageAttrsEnabled.
|
||||
ImageAttrsEnabled bool `yaml:"image_attrs_enabled,omitempty" json:"image_attrs_enabled,omitempty"` //nolint:lll // one-line struct tag
|
||||
ImageAttrsEnabled bool `yaml:"image_attrs_enabled,omitempty" json:"image_attrs_enabled,omitempty" extensions:"x-agent"` //nolint:lll // one-line struct tag
|
||||
// ImageVectorEnabled lets a knowledge base whose embedding model takes
|
||||
// images index each image by its own vector and recall it with one. It
|
||||
// is off by default on purpose: a model that takes images is also used
|
||||
// for plain text, and turning this on costs an embedding call per image
|
||||
// and widens vector recall. Existing knowledge bases stay off after an
|
||||
// upgrade because the stored JSON has no such key.
|
||||
ImageVectorEnabled bool `yaml:"image_vector_enabled,omitempty" json:"image_vector_enabled,omitempty"` //nolint:lll // one-line struct tag
|
||||
ImageVectorEnabled bool `yaml:"image_vector_enabled,omitempty" json:"image_vector_enabled,omitempty" extensions:"x-agent"` //nolint:lll // one-line struct tag
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface, used to convert ChunkingConfig to database value
|
||||
|
|
@ -598,14 +605,14 @@ func (c *ImageProcessingConfig) Scan(value interface{}) error {
|
|||
|
||||
// VLMConfig represents the VLM configuration
|
||||
type VLMConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
ModelID string `yaml:"model_id" json:"model_id"`
|
||||
// DescriptionLanguage controls the language used for generated image
|
||||
// captions. Empty means follow the document/request language.
|
||||
DescriptionLanguage string `yaml:"description_language,omitempty" json:"description_language,omitempty"`
|
||||
// CustomInstructions adds KB-specific image interpretation guidance without
|
||||
// replacing the system-owned OCR and Markdown output contract.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty"`
|
||||
// Enabled turns image captions on. Also send vlm_model_id.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=vlm_enabled"`
|
||||
// Model that writes image captions. model.list returns the ids.
|
||||
ModelID string `yaml:"model_id" json:"model_id" extensions:"x-agent=vlm_model_id"`
|
||||
// DescriptionLanguage is the language of generated image captions. Empty follows the document language.
|
||||
DescriptionLanguage string `yaml:"description_language,omitempty" json:"description_language,omitempty" extensions:"x-agent=vlm_language"`
|
||||
// CustomInstructions adds image-reading guidance. The OCR and Markdown format stay fixed.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty" extensions:"x-agent=vlm_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
|
||||
// 兼容老版本
|
||||
// Model Name
|
||||
|
|
@ -637,12 +644,12 @@ func (c VLMConfig) IsEnabled() bool {
|
|||
// When enabled, the system will use LLM to generate questions for each chunk during document parsing
|
||||
// These generated questions will be indexed separately to improve recall
|
||||
type QuestionGenerationConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
// Number of questions to generate per chunk (default: 3, max: 10)
|
||||
QuestionCount int `yaml:"question_count" json:"question_count"`
|
||||
// CustomInstructions describes the intended audience or question style.
|
||||
// It is appended to the stable system question-generation template.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty"`
|
||||
// Enabled turns question generation on. Generated questions are indexed beside the chunk.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=question_generation_enabled"`
|
||||
// QuestionCount is how many questions to write per chunk, from 1 to 10.
|
||||
QuestionCount int `yaml:"question_count" json:"question_count" minimum:"1" maximum:"10" extensions:"x-agent=question_count"`
|
||||
// CustomInstructions describes who the questions are for. The question format stays fixed.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty" extensions:"x-agent=question_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface
|
||||
|
|
@ -681,9 +688,12 @@ func (c *VLMConfig) Scan(value interface{}) error {
|
|||
|
||||
// ASRConfig represents the ASR (Automatic Speech Recognition) configuration
|
||||
type ASRConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
ModelID string `yaml:"model_id" json:"model_id"`
|
||||
Language string `yaml:"language" json:"language"` // optional: language hint for transcription
|
||||
// Enabled turns speech transcription on. Also send asr_model_id.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=asr_enabled"`
|
||||
// Model that transcribes audio. model.list returns the ids.
|
||||
ModelID string `yaml:"model_id" json:"model_id" extensions:"x-agent=asr_model_id"`
|
||||
// Language is an optional hint for transcription, such as zh or en.
|
||||
Language string `yaml:"language" json:"language" extensions:"x-agent=asr_language"`
|
||||
}
|
||||
|
||||
// IsASREnabled checks if ASR is enabled with a valid model
|
||||
|
|
@ -710,14 +720,16 @@ func (c *ASRConfig) Scan(value interface{}) error {
|
|||
|
||||
// ExtractConfig represents the extract configuration for a knowledge base
|
||||
type ExtractConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Text string `yaml:"text" json:"text,omitempty"`
|
||||
Tags []string `yaml:"tags" json:"tags,omitempty"`
|
||||
// Enabled turns graph extraction on. Node and relation types are edited in the knowledge base editor.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=extract_enabled"`
|
||||
// Text is the extraction prompt. Required when extraction is on and no text is saved yet.
|
||||
Text string `yaml:"text" json:"text,omitempty" extensions:"x-agent=extract_text,x-agent-detail,x-agent-max-bytes=8000"`
|
||||
// Tags are the entity labels extraction may use.
|
||||
Tags []string `yaml:"tags" json:"tags,omitempty" extensions:"x-agent=extract_tags,x-agent-maximum=50"`
|
||||
Nodes []*GraphNode `yaml:"nodes" json:"nodes,omitempty"`
|
||||
Relations []*GraphRelation `yaml:"relations" json:"relations,omitempty"`
|
||||
// CustomInstructions adds domain-specific extraction guidance while the
|
||||
// system keeps ownership of the structured graph output protocol.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty"`
|
||||
// CustomInstructions adds domain guidance. The graph output format stays fixed.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty" extensions:"x-agent=extract_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface, used to convert ExtractConfig to database value
|
||||
|
|
@ -739,8 +751,10 @@ func (e *ExtractConfig) Scan(value interface{}) error {
|
|||
|
||||
// FAQConfig 存储 FAQ 知识库的特有配置
|
||||
type FAQConfig struct {
|
||||
IndexMode FAQIndexMode `yaml:"index_mode" json:"index_mode"`
|
||||
QuestionIndexMode FAQQuestionIndexMode `yaml:"question_index_mode" json:"question_index_mode"`
|
||||
// IndexMode is question_only or question_answer.
|
||||
IndexMode FAQIndexMode `yaml:"index_mode" json:"index_mode" enums:"question_only,question_answer" extensions:"x-agent=faq_index_mode"`
|
||||
// QuestionIndexMode is combined or separate.
|
||||
QuestionIndexMode FAQQuestionIndexMode `yaml:"question_index_mode" json:"question_index_mode" enums:"combined,separate" extensions:"x-agent=faq_question_index_mode"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer
|
||||
|
|
|
|||
|
|
@ -59,12 +59,12 @@ const (
|
|||
// KnowledgeBaseProfileConfig controls automatic generation of the knowledge
|
||||
// base description. It is opt-in so upgrading a deployment adds no model calls.
|
||||
type KnowledgeBaseProfileConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
// ModelID overrides the chat model; empty falls back to the KB summary model.
|
||||
ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty"`
|
||||
// CustomInstructions is appended to the stable system prompt, e.g. the
|
||||
// audience the description should address or terms to keep.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty"`
|
||||
// Enabled turns the AI knowledge-base description on.
|
||||
Enabled bool `yaml:"enabled" json:"enabled" extensions:"x-agent=profile_enabled"`
|
||||
// ModelID overrides the summary model. Empty uses summary_model_id.
|
||||
ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty" extensions:"x-agent=profile_model_id"`
|
||||
// CustomInstructions is extra guidance for the description, such as the audience. The format stays fixed.
|
||||
CustomInstructions string `yaml:"custom_instructions,omitempty" json:"custom_instructions,omitempty" extensions:"x-agent=profile_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
}
|
||||
|
||||
// IsEnabled reports whether automatic generation is on for a nil-safe receiver.
|
||||
|
|
|
|||
|
|
@ -535,19 +535,16 @@ func (g WikiExtractionGranularity) Normalize() WikiExtractionGranularity {
|
|||
// Whether the wiki feature is turned on is controlled by IndexingStrategy.WikiEnabled;
|
||||
// this struct only carries wiki-specific tunables.
|
||||
type WikiConfig struct {
|
||||
// SynthesisModelID is the LLM model ID used for wiki page generation and updates
|
||||
SynthesisModelID string `yaml:"synthesis_model_id" json:"synthesis_model_id"`
|
||||
// MaxPagesPerIngest limits pages created/updated per ingest operation (0 = no limit)
|
||||
MaxPagesPerIngest int `yaml:"max_pages_per_ingest" json:"max_pages_per_ingest"`
|
||||
// ExtractionGranularity controls how many candidate slugs Pass 0 extracts
|
||||
// per document. Empty / unknown value is treated as WikiExtractionStandard.
|
||||
ExtractionGranularity WikiExtractionGranularity `yaml:"extraction_granularity" json:"extraction_granularity,omitempty"`
|
||||
// ContentInstructions controls tone, structure and emphasis for generated
|
||||
// summary/entity/index prose. Citation and merge rules remain system-owned.
|
||||
ContentInstructions string `yaml:"content_instructions,omitempty" json:"content_instructions,omitempty"`
|
||||
// ExtractionInstructions tells candidate extraction which domain concepts
|
||||
// to emphasize without replacing the stable JSON/citation protocol.
|
||||
ExtractionInstructions string `yaml:"extraction_instructions,omitempty" json:"extraction_instructions,omitempty"`
|
||||
// SynthesisModelID is the model that writes Wiki pages. Empty uses summary_model_id.
|
||||
SynthesisModelID string `yaml:"synthesis_model_id" json:"synthesis_model_id" extensions:"x-agent=wiki_synthesis_model_id"`
|
||||
// MaxPagesPerIngest limits pages created or updated per ingest. 0 means no limit.
|
||||
MaxPagesPerIngest int `yaml:"max_pages_per_ingest" json:"max_pages_per_ingest" minimum:"0" maximum:"1000" extensions:"x-agent=wiki_max_pages"`
|
||||
// ExtractionGranularity is focused, standard or exhaustive. Empty means standard.
|
||||
ExtractionGranularity WikiExtractionGranularity `yaml:"extraction_granularity" json:"extraction_granularity,omitempty" enums:"focused,standard,exhaustive" extensions:"x-agent=wiki_granularity"`
|
||||
// ContentInstructions sets tone and emphasis for generated Wiki prose. Citations stay fixed.
|
||||
ContentInstructions string `yaml:"content_instructions,omitempty" json:"content_instructions,omitempty" extensions:"x-agent=wiki_content_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
// ExtractionInstructions tells page extraction which concepts to keep. The output format stays fixed.
|
||||
ExtractionInstructions string `yaml:"extraction_instructions,omitempty" json:"extraction_instructions,omitempty" extensions:"x-agent=wiki_extraction_instructions,x-agent-detail,x-agent-max-bytes=4000"`
|
||||
|
||||
// Wiki ingest concurrency is two-level:
|
||||
// 1. batch-level: multiple batches per KB run concurrently in the wiki
|
||||
|
|
|
|||
|
|
@ -182,14 +182,14 @@ curl -X PUT $BASE/api/v1/knowledge-bases/kb-1/tags/t-1 -H "Authorization: Bearer
|
|||
|
||||
### DELETE /api/v1/knowledge-bases/:id/tags/:tag_id
|
||||
|
||||
用途:删除标签。查询参数:`force`(bool,强制删除被引用的标签)、`content_only`(bool,仅删除标签下的内容、保留标签)。请求体(可选):`{"exclude_ids":[int64]}`,列出删除时保留的 FAQ 条目 seq_id。
|
||||
用途:删除标签。查询参数:`force`(bool,连同仍引用该标签的文档或 FAQ 条目一起删除)、`content_only`(bool,仅删除标签下的内容、保留标签)。请求体(可选):`{"exclude_ids":[int64]}`,列出删除时保留的 FAQ 条目 seq_id。不传 `force` 时,仍有知识或 FAQ 引用该标签会返回 400,文档不会被删除。
|
||||
|
||||
请求体格式不合法或 ID 非正整数返回 400;ID 不存在返回 404;ID 不属于当前知识库的 FAQ 条目返回 403。
|
||||
|
||||
响应:200 `{"success":true}`
|
||||
|
||||
```bash
|
||||
curl -X DELETE "$BASE/api/v1/knowledge-bases/kb-1/tags/t-1?force=true" -H "Authorization: Bearer $TOKEN"
|
||||
curl -X DELETE $BASE/api/v1/knowledge-bases/kb-1/tags/t-1 -H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
## 分块调试
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@
|
|||
|
||||
响应:201 `{"success":true,"data":{KnowledgeBase}}`
|
||||
|
||||
`indexing_strategy` 里没写到的开关保持默认:向量和关键词开启,Wiki 和图谱关闭。显式传 `false` 才会关掉。
|
||||
|
||||
```bash
|
||||
curl -X POST $BASE/api/v1/knowledge-bases -H "Authorization: Bearer $TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{"name":"产品文档","type":"document"}'
|
||||
|
|
@ -110,6 +112,28 @@ curl -X PUT $BASE/api/v1/knowledge-bases/kb-1 -H "Authorization: Bearer $TOKEN"
|
|||
-H 'Content-Type: application/json' -d '{"name":"产品文档 v2"}'
|
||||
```
|
||||
|
||||
### PATCH /api/v1/knowledge-bases/:id
|
||||
|
||||
用途:只修改请求里出现的设置,其余保持不变。这包括名称、描述、模型、存储、分块、索引开关、FAQ、Wiki、自动标签、AI 描述、图片、语音和图谱提取里的字段:嵌套对象中没写到的字段也保持原值。权限与 PUT 相同;修改嵌入模型、摘要模型、多模态或语音时,共享知识库还需要管理员共享权限。存储实例只能由知识库所属空间修改,且知识库中已有文件时必须先迁移存储;共享管理员可以原样回传当前存储 ID,但不能更换。`embedding_model_id` 在知识库已有文档时不能改。`vector_store_id` 只能在创建时指定。`name` 传了就不能为空;`description` 传空字符串会清空描述。
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | string | 否 | 新名称 |
|
||||
| `description` | string | 否 | 新描述;空字符串清空 |
|
||||
| `embedding_model_id` / `summary_model_id` / `storage_backend_id` | string | 否 | 模型或存储实例 |
|
||||
| `chunking_config` | object | 否 | 只覆盖写到的分块字段 |
|
||||
| `indexing_strategy` | object | 否 | 只覆盖写到的开关;至少保留一种索引 |
|
||||
| `vlm_config` / `asr_config` / `image_processing_config` | object | 否 | 多模态、语音、图片 |
|
||||
| `faq_config` / `wiki_config` / `auto_tag_config` / `profile_config` | object | 否 | 类型相关设置 |
|
||||
| `extract_config` / `question_generation_config` | object | 否 | 图谱提取、分块问题生成 |
|
||||
|
||||
响应:200 `{"success":true,"data":{KnowledgeBase}}`
|
||||
|
||||
```bash
|
||||
curl -X PATCH $BASE/api/v1/knowledge-bases/kb-1 -H "Authorization: Bearer $TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{"name":"产品文档 v2"}'
|
||||
```
|
||||
|
||||
### DELETE /api/v1/knowledge-bases/:id
|
||||
|
||||
用途:删除知识库(锁定为属主空间 + Admin;共享 editor 不可删)。权限:创建者 OR Admin+,KB write;API key `manage_kbs`/full。
|
||||
|
|
@ -526,7 +550,7 @@ curl -X POST $BASE/api/v1/knowledge/k-1/regenerate-summary -H "Authorization: Be
|
|||
|
||||
### PUT /api/v1/knowledge/manual/:id
|
||||
|
||||
用途:更新手工知识内容(`ManualKnowledgePayload` 子集:`title/content/status/...`)。权限同上。
|
||||
用途:整篇替换手工录入的 Markdown。只适用于手工知识;上传文件不能用这个接口改正文。`content` 是完整正文,空内容会被拒绝。`status` 为 `draft`(不进入检索)或 `publish`(建立索引);不传 `status` 时按草稿保存。权限同上。
|
||||
|
||||
响应:200 `{"success":true,"data":{Knowledge}}`
|
||||
|
||||
|
|
@ -617,12 +641,14 @@ curl $BASE/api/v1/knowledge/move/progress/task-1 -H "Authorization: Bearer $TOKE
|
|||
|
||||
### PUT /api/v1/knowledge/tags
|
||||
|
||||
用途:批量更新知识标签。权限:Contributor+;API key `ingest`/full(KB 白名单在 handler 校验)。
|
||||
用途:批量更新知识标签。权限:Contributor+;API key `ingest`/full(KB 白名单在 handler 校验)。两种写法互斥:`updates`,或 `knowledge_ids` 加 `tag_ids`。
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `updates` | map[string][]string | 是(`binding:"required,min=1"`) | knowledge_id → tag_ids |
|
||||
| `kb_id` | string | 否 | 限定 KB |
|
||||
| `updates` | map[string][]string | 与 `knowledge_ids` 二选一 | knowledge_id → tag_ids,替换该文档现有标签 |
|
||||
| `kb_id` | string | 否 | 限定知识库;不传时从第一条知识推断 |
|
||||
| `knowledge_ids` | []string | 与 `updates` 二选一 | 最多 20 篇,同一组标签 |
|
||||
| `tag_ids` | []string | 使用 `knowledge_ids` 时必填 | 最多 50 个;空数组清空标签 |
|
||||
|
||||
响应:200 `{"success":true}`
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue