From 2fbfb4471581cd5e7d731bc7a2d443fe7d8e95b5 Mon Sep 17 00:00:00 2001 From: lyingbug Date: Thu, 15 Oct 2026 23:54:14 +0800 Subject: [PATCH] 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 fields --- client/knowledge.go | 10 +- client/knowledge_tags_test.go | 31 + client/knowledgebase.go | 92 ++ client/knowledgebase_patch_test.go | 67 ++ .../prompt_templates/agent_system_prompt.yaml | 5 + docs/docs.go | 845 +++++++++++++++--- docs/swagger.json | 845 +++++++++++++++--- docs/swagger.yaml | 605 +++++++++++-- frontend/src/i18n/locales/en-US.ts | 42 +- frontend/src/i18n/locales/ja-JP.ts | 42 +- frontend/src/i18n/locales/ko-KR.ts | 42 +- frontend/src/i18n/locales/ru-RU.ts | 42 +- frontend/src/i18n/locales/zh-CN.ts | 42 +- frontend/src/i18n/locales/zh-TW.ts | 42 +- .../ToolApprovalCard.description.test.mjs | 27 +- .../chat/components/ToolApprovalCard.vue | 91 +- .../components/agent-interaction-card.less | 30 + internal/agent/operations/catalog_test.go | 65 ++ internal/agent/operations/request.go | 33 +- internal/agent/operations/spec.go | 83 +- internal/agent/operations/spec_test.go | 70 ++ internal/agent/tools/operations.go | 42 +- internal/agent/tools/operations_test.go | 31 +- internal/application/service/knowledgebase.go | 122 +++ .../knowledgebase_storage_update_test.go | 150 ++++ internal/handler/knowledge.go | 76 +- internal/handler/knowledge_tag_batch_test.go | 36 + internal/handler/knowledgebase.go | 381 +++++++- internal/handler/knowledgebase_patch_test.go | 72 ++ .../knowledgebase_settings_access_test.go | 95 ++ internal/handler/tag.go | 36 +- .../router_api_key_capabilities_test.go | 1 + internal/router/routes_knowledge.go | 1 + internal/types/knowledge.go | 4 +- internal/types/knowledgebase.go | 194 ++-- internal/types/knowledgebase_profile.go | 12 +- internal/types/wiki_page.go | 23 +- website-docs/04-api/02-api-chunks.md | 4 +- website-docs/04-api/02-api-knowledge.md | 34 +- 39 files changed, 3928 insertions(+), 537 deletions(-) create mode 100644 client/knowledge_tags_test.go create mode 100644 client/knowledgebase_patch_test.go create mode 100644 internal/application/service/knowledgebase_storage_update_test.go create mode 100644 internal/handler/knowledge_tag_batch_test.go create mode 100644 internal/handler/knowledgebase_patch_test.go create mode 100644 internal/handler/knowledgebase_settings_access_test.go diff --git a/client/knowledge.go b/client/knowledge.go index fc98987c..a551818f 100644 --- a/client/knowledge.go +++ b/client/knowledge.go @@ -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. diff --git a/client/knowledge_tags_test.go b/client/knowledge_tags_test.go new file mode 100644 index 00000000..9a1eddb6 --- /dev/null +++ b/client/knowledge_tags_test.go @@ -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) + } + } +} diff --git a/client/knowledgebase.go b/client/knowledgebase.go index be63e228..d2b23aef 100644 --- a/client/knowledgebase.go +++ b/client/knowledgebase.go @@ -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) diff --git a/client/knowledgebase_patch_test.go b/client/knowledgebase_patch_test.go new file mode 100644 index 00000000..8c3f1513 --- /dev/null +++ b/client/knowledgebase_patch_test.go @@ -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) + } + }) + } +} diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yaml index 5d564b48..229fda50 100644 --- a/config/prompt_templates/agent_system_prompt.yaml +++ b/config/prompt_templates/agent_system_prompt.yaml @@ -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. diff --git a/docs/docs.go b/docs/docs.go index a07d99f8..fa23d045 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4401,7 +4401,13 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.create", + "label_param": "name", + "risk": "write" + }, + "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." } }, "/knowledge-bases/copy": { @@ -4721,6 +4727,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -4752,7 +4759,99 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.delete", + "label": "name", + "risk": "destructive", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Deletes the knowledge base and every document in it. Cannot be undone. Only the owner can delete it." + }, + "patch": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "修改请求里出现的设置。未出现的字段保持不变,包括分块、索引和模型里没写到的项。", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "知识库" + ], + "summary": "部分更新知识库", + "parameters": [ + { + "type": "string", + "x-agent": "knowledge_base_id", + "description": "知识库ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "要修改的字段", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/internal_handler.PatchKnowledgeBaseRequest" + } + } + ], + "responses": { + "200": { + "description": "更新后的知识库", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/internal_handler.DataResponse" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/internal_handler.KnowledgeBaseView" + } + } + } + ] + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "403": { + "description": "无权限", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "404": { + "description": "知识库不存在", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + }, + "x-agent": { + "id": "knowledge_base.update", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge-bases/{id}/activity": { @@ -6775,7 +6874,7 @@ const docTemplate = `{ "risk": "write", "target": "knowledge_base.get" }, - "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." } }, "/knowledge-bases/{id}/knowledge/url": { @@ -7397,6 +7496,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7408,18 +7508,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "type": "object", - "properties": { - "color": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sort_order": { - "type": "integer" - } - } + "$ref": "#/definitions/internal_handler.CreateTagRequest" } } ], @@ -7448,7 +7537,14 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.create_tag", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Creates a tag in the knowledge base. Pass the returned tag id to knowledge.set_tags." } }, "/knowledge-bases/{id}/tags/{tag_id}": { @@ -7475,6 +7571,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7482,6 +7579,7 @@ const docTemplate = `{ }, { "type": "string", + "x-agent": "tag_id", "description": "标签ID (UUID或seq_id)", "name": "tag_id", "in": "path", @@ -7493,7 +7591,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "type": "object" + "$ref": "#/definitions/internal_handler.UpdateTagRequest" } } ], @@ -7522,7 +7620,14 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.update_tag", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Renames a tag. tag_id comes from knowledge_base.list_tags. A field left out is kept." }, "delete": { "security": [ @@ -7547,6 +7652,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7554,6 +7660,7 @@ const docTemplate = `{ }, { "type": "string", + "x-agent": "tag_id", "description": "标签ID (UUID或seq_id)", "name": "tag_id", "in": "path", @@ -7593,7 +7700,14 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.delete_tag", + "label": "name", + "risk": "destructive", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge-chat/{session_id}": { @@ -8091,6 +8205,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", + "x-agent": "knowledge_id", "description": "知识ID", "name": "id", "in": "path", @@ -8131,7 +8246,14 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge.update_manual", + "label": "title", + "risk": "write", + "target": "knowledge.get" + }, + "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." } }, "/knowledge/move": { @@ -8355,7 +8477,7 @@ const docTemplate = `{ "ApiKeyAuth": [] } ], - "description": "批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析", + "description": "批量更新知识条目的标签。传 updates,或传 knowledge_ids 与 tag_ids。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析", "consumes": [ "application/json" ], @@ -8368,12 +8490,12 @@ const docTemplate = `{ "summary": "批量更新知识标签", "parameters": [ { - "description": "标签更新请求(updates 必填,kb_id 可选)", + "description": "标签更新请求", "name": "request", "in": "body", "required": true, "schema": { - "type": "object" + "$ref": "#/definitions/internal_handler.KnowledgeTagBatchRequest" } } ], @@ -8390,7 +8512,20 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge.set_tags", + "items": { + "as": "knowledge_id", + "label": "title", + "param": "knowledge_ids", + "target": "knowledge.get" + }, + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge/{id}": { @@ -22890,14 +23025,19 @@ const docTemplate = `{ "type": "object", "properties": { "enabled": { - "type": "boolean" + "description": "Enabled turns speech transcription on. Also send asr_model_id.", + "type": "boolean", + "x-agent": "asr_enabled" }, "language": { - "description": "optional: language hint for transcription", - "type": "string" + "description": "Language is an optional hint for transcription, such as zh or en.", + "type": "string", + "x-agent": "asr_language" }, "model_id": { - "type": "string" + "description": "Model that transcribes audio. model.list returns the ids.", + "type": "string", + "x-agent": "asr_model_id" } } }, @@ -23399,17 +23539,26 @@ const docTemplate = `{ "type": "object", "properties": { "enabled": { - "type": "boolean" + "description": "Enabled turns automatic tagging on. The model picks from tags that already exist.", + "type": "boolean", + "x-agent": "auto_tag_enabled" }, "max_tags": { - "type": "integer" + "description": "MaxTags is how many tags one document may receive, from 1 to 10.", + "type": "integer", + "maximum": 10, + "minimum": 1, + "x-agent": "auto_tag_max_tags" }, "model_id": { - "type": "string" + "description": "ModelID overrides the summary model. Empty uses summary_model_id.", + "type": "string", + "x-agent": "auto_tag_model_id" }, "skip_if_tagged": { - "description": "SkipIfTagged leaves documents that already carry tags untouched, so a\ndeliberate manual classification is not diluted by model guesses. It is\na pointer because the default is true: rows written before this field\nexisted decode to nil and must not silently flip to \"always append\".", - "type": "boolean" + "description": "SkipIfTagged leaves a document alone when it already has tags. Empty means yes.", + "type": "boolean", + "x-agent": "auto_tag_skip_if_tagged" } } }, @@ -23790,30 +23939,45 @@ const docTemplate = `{ "properties": { "child_chunk_size": { "description": "ChildChunkSize is the size of child chunks used for embedding (default: 384).\nOnly used when EnableParentChild is true.", - "type": "integer" + "type": "integer", + "maximum": 10000, + "minimum": 1, + "x-agent": true }, "chunk_overlap": { - "description": "Chunk overlap", - "type": "integer" + "description": "Chunk overlap in characters.", + "type": "integer", + "maximum": 5000, + "minimum": 0, + "x-agent": true }, "chunk_size": { - "description": "Chunk size", - "type": "integer" + "description": "Chunk size in characters. Empty on create uses the server default.", + "type": "integer", + "maximum": 10000, + "minimum": 100, + "x-agent": true }, "enable_parent_child": { - "description": "EnableParentChild enables two-level parent-child chunking strategy.\nWhen enabled, large parent chunks provide context while small child chunks\nare used for vector matching. Retrieval matches on child but returns parent content.", - "type": "boolean" + "description": "EnableParentChild splits into large parent chunks and small child chunks. Search matches a child and returns its parent.", + "type": "boolean", + "x-agent": true }, "languages": { - "description": "Languages hints the heuristic patterns. Empty = auto-detect from content.\nExamples: [\"de\"], [\"en\", \"zh\"].", + "description": "Languages hints the splitter, for example de or zh. Empty detects the language from the document.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": true, + "x-agent-maximum": "20" }, "parent_chunk_size": { "description": "ParentChunkSize is the size of parent chunks (default: 4096).\nOnly used when EnableParentChild is true.", - "type": "integer" + "type": "integer", + "maximum": 20000, + "minimum": 1, + "x-agent": true }, "parser_engine_rules": { "description": "ParserEngineRules configures which parser engine to use for each file type.\nWhen empty, DefaultParserEngine is used (builtin/simple routing, except\ntypes that only a specific engine can parse: ppt/pptx fall back to\nmarkitdown). A linked anydoc binding is preferred for every type it\nconverts.", @@ -23823,23 +23987,39 @@ const docTemplate = `{ } }, "separators": { - "description": "Separators", + "description": "Separators, in the order they are tried.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": true, + "x-agent-maximum": "20" }, "strategy": { - "description": "Strategy selects the adaptive chunking tier. Empty / \"legacy\" preserves\nthe historical recursive splitter; \"auto\" lets a profiler pick between\nheading-aware, heuristic and recursive tiers; \"heading\" / \"heuristic\" /\n\"recursive\" pin the tier explicitly.", - "type": "string" + "description": "Strategy selects how documents are split: auto, heading, heuristic, recursive or legacy. Empty keeps the server default.", + "type": "string", + "enum": [ + "auto", + "heading", + "heuristic", + "recursive", + "legacy" + ], + "x-agent": true }, "table_metadata_instructions": { - "description": "TableMetadataInstructions contains optional business guidance used when\ngenerating searchable summaries for CSV/Excel tables. The system-owned\noutput contract remains fixed; these instructions only add domain context.", - "type": "string" + "description": "TableMetadataInstructions is extra guidance for CSV and Excel summaries. The output format stays fixed.", + "type": "string", + "x-agent": true, + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "token_limit": { - "description": "TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize\nas a character count.", - "type": "integer" + "description": "TokenLimit caps chunk size in approximate tokens. 0 uses ChunkSize as a character count.", + "type": "integer", + "maximum": 100000, + "minimum": 0, + "x-agent": true } } }, @@ -24732,11 +24912,16 @@ const docTemplate = `{ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions adds domain-specific extraction guidance while the\nsystem keeps ownership of the structured graph output protocol.", - "type": "string" + "description": "CustomInstructions adds domain guidance. The graph output format stays fixed.", + "type": "string", + "x-agent": "extract_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns graph extraction on. Node and relation types are edited in the knowledge base editor.", + "type": "boolean", + "x-agent": "extract_enabled" }, "nodes": { "type": "array", @@ -24751,13 +24936,20 @@ const docTemplate = `{ } }, "tags": { + "description": "Tags are the entity labels extraction may use.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": "extract_tags", + "x-agent-maximum": "50" }, "text": { - "type": "string" + "description": "Text is the extraction prompt. Required when extraction is on and no text is saved yet.", + "type": "string", + "x-agent": "extract_text", + "x-agent-detail": true, + "x-agent-max-bytes": "8000" } } }, @@ -24797,10 +24989,30 @@ const docTemplate = `{ "type": "object", "properties": { "index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + "description": "IndexMode is question_only or question_answer.", + "enum": [ + "question_only", + "question_answer" + ], + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + } + ], + "x-agent": "faq_index_mode" }, "question_index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + "description": "QuestionIndexMode is combined or separate.", + "enum": [ + "combined", + "separate" + ], + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + } + ], + "x-agent": "faq_question_index_mode" } } }, @@ -25622,15 +25834,18 @@ const docTemplate = `{ }, "image_attrs_enabled": { "description": "ImageAttrsEnabled turns the attribute-observed image pipeline on for this\nknowledge base. It is off by default on purpose, so upgrading an\nexisting deployment never changes what happens to documents already\nbeing ingested: with it off every image is described and OCR'd exactly\nas before. When on, the describe round also observes image attributes and\nthe attribute policy decides whether OCR runs for it. A single upload can\noverride it per document through\nKnowledgeProcessOverrides.ImageAttrsEnabled.", - "type": "boolean" + "type": "boolean", + "x-agent": true }, "image_vector_enabled": { "description": "ImageVectorEnabled lets a knowledge base whose embedding model takes\nimages index each image by its own vector and recall it with one. It\nis off by default on purpose: a model that takes images is also used\nfor plain text, and turning this on costs an embedding call per image\nand widens vector recall. Existing knowledge bases stay off after an\nupgrade because the stored JSON has no such key.", - "type": "boolean" + "type": "boolean", + "x-agent": true }, "model_id": { - "description": "Model ID", - "type": "string" + "description": "Model ID used when describing images. Empty uses the knowledge base's caption model.", + "type": "string", + "x-agent": "image_model_id" } } }, @@ -26140,6 +26355,9 @@ const docTemplate = `{ }, "github_com_Tencent_WeKnora_internal_types.KnowledgeBase": { "type": "object", + "required": [ + "name" + ], "properties": { "asr_config": { "description": "ASR config (Automatic Speech Recognition)", @@ -26147,7 +26365,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "auto_tag_config": { "description": "AutoTagConfig controls asynchronous association of existing tags after parsing.", @@ -26155,12 +26375,15 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "chunking_config": { "description": "Chunking configuration", @@ -26168,7 +26391,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "created_at": { "description": "Creation time of the knowledge base", @@ -26196,8 +26421,9 @@ const docTemplate = `{ "x-agent": true }, "embedding_model_id": { - "description": "ID of the embedding model", - "type": "string" + "description": "ID of the embedding model. model.list returns the ids. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" }, "extract_config": { "description": "Extract config", @@ -26205,7 +26431,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "faq_config": { "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", @@ -26213,7 +26441,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "generated_profile": { "description": "GeneratedProfile is the machine-generated description: a gist, merged\ntopics, typical questions and the aggregate snapshot they came from. It\nnever overwrites the user-authored Description; both are shown to agents.", @@ -26226,7 +26456,8 @@ const docTemplate = `{ "id": { "description": "Unique identifier of the knowledge base", "type": "string", - "x-agent": "knowledge_base_id" + "x-agent": "knowledge_base_id", + "x-agent-response": true }, "image_processing_config": { "description": "Image processing configuration", @@ -26234,7 +26465,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "indexing_strategy": { "description": "IndexingStrategy controls which indexing pipelines are active for this knowledge base.\nPipelines: vector search, keyword search, wiki generation, knowledge graph extraction.", @@ -26243,7 +26476,8 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" } ], - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_pinned": { "description": "IsPinned and PinnedAt are computed per-caller from user_kb_pins\n(see migration 000050). They used to be stored on the row itself,\nwhich made pinning a workspace-wide ordering decision gated behind\nthe kb-edit RBAC guard. The columns are still present in legacy\nschemas for rollback safety but are no longer read or written by\nthe application — both fields are tagged ` + "`" + `gorm:\"-\"` + "`" + ` so GORM\nignores them on every CRUD call and the list handler stamps them\nafter enriching with the caller's pin set.", @@ -26252,7 +26486,8 @@ const docTemplate = `{ "is_processing": { "description": "IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases)", "type": "boolean", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_temporary": { "description": "Whether this knowledge base is temporary (ephemeral) and should be hidden from UI", @@ -26261,12 +26496,14 @@ const docTemplate = `{ "knowledge_count": { "description": "Knowledge count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "name": { "description": "Name of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "pinned_at": { "description": "PinnedAt records when the current caller pinned this knowledge\nbase; nil when they have not.", @@ -26275,7 +26512,8 @@ const docTemplate = `{ "processing_count": { "description": "ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "profile_config": { "description": "ProfileConfig controls automatic generation of the knowledge-base\ndescription from per-document profiles (document knowledge bases only).", @@ -26283,7 +26521,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "question_generation_config": { "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", @@ -26291,7 +26531,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "share_count": { "description": "ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)", @@ -26299,7 +26541,8 @@ const docTemplate = `{ }, "storage_backend_id": { "description": "StorageBackendID binds this KB to one concrete storage instance. The\nlegacy provider field remains readable during migration only.", - "type": "string" + "type": "string", + "x-agent": "storage_backend_id" }, "storage_config": { "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", @@ -26318,26 +26561,34 @@ const docTemplate = `{ ] }, "summary_model_id": { - "description": "Summary model ID", - "type": "string" + "description": "Summary model ID. model.list returns the ids. Used for summaries, and as the default for auto-tagging and the AI description.", + "type": "string", + "x-agent": "summary_model_id" }, "tenant_id": { "description": "Workspace ID", "type": "integer" }, "type": { - "description": "Type of the knowledge base (document, faq, etc.)", + "description": "Type of the knowledge base: document, faq or wiki. Empty means document.", "type": "string", + "enum": [ + "document", + "faq", + "wiki" + ], "x-agent": true }, "updated_at": { "description": "Last updated time of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "vector_store_id": { "description": "VectorStoreID references the VectorStore this knowledge base is bound to.\nWhen nil, the KB falls back to the workspace's effective engines derived from\nthe RETRIEVE_DRIVER environment variable (env store flow).\nThis field is set once at creation time and must not be modified afterwards;\nenforcement lives at the GORM layer (` + "`" + `\u003c-:create` + "`" + `) plus the service-layer\nKB update path, which omits this field from its update DTO.", - "type": "string" + "type": "string", + "x-agent": "vector_store_id" }, "vlm_config": { "description": "VLM config", @@ -26345,7 +26596,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "wiki_config": { "description": "WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases)", @@ -26353,13 +26606,23 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true } } }, "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig": { "type": "object", "properties": { + "asr_config": { + "description": "ASRConfig replaces speech-recognition settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" + } + ] + }, "auto_tag_config": { "description": "AutoTagConfig controls optional automatic association of existing KB tags.", "allOf": [ @@ -26376,6 +26639,18 @@ const docTemplate = `{ } ] }, + "embedding_model_id": { + "description": "EmbeddingModelID changes the embedding model. nil means no change.\nA knowledge base that already has documents cannot switch models.", + "type": "string" + }, + "extract_config": { + "description": "ExtractConfig replaces graph extraction settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + } + ] + }, "faq_config": { "description": "FAQ configuration (only for FAQ type knowledge bases)", "allOf": [ @@ -26408,6 +26683,22 @@ const docTemplate = `{ } ] }, + "question_generation_config": { + "description": "QuestionGenerationConfig replaces generated-question settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + } + ] + }, + "storage_backend_id": { + "description": "StorageBackendID rebinds file storage. nil means no change.", + "type": "string" + }, + "summary_model_id": { + "description": "SummaryModelID changes the summary model. nil means no change.", + "type": "string" + }, "wiki_config": { "description": "Wiki configuration (only for wiki-enabled knowledge bases)", "allOf": [ @@ -26479,15 +26770,21 @@ const docTemplate = `{ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions is appended to the stable system prompt, e.g. the\naudience the description should address or terms to keep.", - "type": "string" + "description": "CustomInstructions is extra guidance for the description, such as the audience. The format stays fixed.", + "type": "string", + "x-agent": "profile_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns the AI knowledge-base description on.", + "type": "boolean", + "x-agent": "profile_enabled" }, "model_id": { - "description": "ModelID overrides the chat model; empty falls back to the KB summary model.", - "type": "string" + "description": "ModelID overrides the summary model. Empty uses summary_model_id.", + "type": "string", + "x-agent": "profile_model_id" } } }, @@ -27353,7 +27650,8 @@ const docTemplate = `{ "description": "Markdown content. The assistant may send a full document; the API limit\nis 200000 runes, and x-agent-max-bytes covers that in UTF-8.", "type": "string", "x-agent": true, - "x-agent-max-bytes": "800000" + "x-agent-max-bytes": "800000", + "x-agent-required": true }, "process_config": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeProcessOverrides" @@ -27365,7 +27663,8 @@ const docTemplate = `{ "draft", "publish" ], - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "tag_ids": { "type": "array", @@ -29117,15 +29416,23 @@ const docTemplate = `{ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions describes the intended audience or question style.\nIt is appended to the stable system question-generation template.", - "type": "string" + "description": "CustomInstructions describes who the questions are for. The question format stays fixed.", + "type": "string", + "x-agent": "question_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns question generation on. Generated questions are indexed beside the chunk.", + "type": "boolean", + "x-agent": "question_generation_enabled" }, "question_count": { - "description": "Number of questions to generate per chunk (default: 3, max: 10)", - "type": "integer" + "description": "QuestionCount is how many questions to write per chunk, from 1 to 10.", + "type": "integer", + "maximum": 10, + "minimum": 1, + "x-agent": "question_count" } } }, @@ -31574,22 +31881,30 @@ const docTemplate = `{ "type": "string" }, "custom_instructions": { - "description": "CustomInstructions adds KB-specific image interpretation guidance without\nreplacing the system-owned OCR and Markdown output contract.", - "type": "string" + "description": "CustomInstructions adds image-reading guidance. The OCR and Markdown format stay fixed.", + "type": "string", + "x-agent": "vlm_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "description_language": { - "description": "DescriptionLanguage controls the language used for generated image\ncaptions. Empty means follow the document/request language.", - "type": "string" + "description": "DescriptionLanguage is the language of generated image captions. Empty follows the document language.", + "type": "string", + "x-agent": "vlm_language" }, "enabled": { - "type": "boolean" + "description": "Enabled turns image captions on. Also send vlm_model_id.", + "type": "boolean", + "x-agent": "vlm_enabled" }, "interface_type": { "description": "Interface Type: \"ollama\" or \"openai\"", "type": "string" }, "model_id": { - "type": "string" + "description": "Model that writes image captions. model.list returns the ids.", + "type": "string", + "x-agent": "vlm_model_id" }, "model_name": { "description": "兼容老版本\nModel Name", @@ -32043,20 +32358,32 @@ const docTemplate = `{ "type": "object", "properties": { "content_instructions": { - "description": "ContentInstructions controls tone, structure and emphasis for generated\nsummary/entity/index prose. Citation and merge rules remain system-owned.", - "type": "string" + "description": "ContentInstructions sets tone and emphasis for generated Wiki prose. Citations stay fixed.", + "type": "string", + "x-agent": "wiki_content_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "extraction_granularity": { - "description": "ExtractionGranularity controls how many candidate slugs Pass 0 extracts\nper document. Empty / unknown value is treated as WikiExtractionStandard.", + "description": "ExtractionGranularity is focused, standard or exhaustive. Empty means standard.", + "enum": [ + "focused", + "standard", + "exhaustive" + ], "allOf": [ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiExtractionGranularity" } - ] + ], + "x-agent": "wiki_granularity" }, "extraction_instructions": { - "description": "ExtractionInstructions tells candidate extraction which domain concepts\nto emphasize without replacing the stable JSON/citation protocol.", - "type": "string" + "description": "ExtractionInstructions tells page extraction which concepts to keep. The output format stays fixed.", + "type": "string", + "x-agent": "wiki_extraction_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "ingest_batch_size": { "description": "IngestBatchSize controls how many pending ops a single batch claims and\nprocesses before scheduling a follow-up. 0 falls back to the hard-coded\ndefault (5). Larger batches amortize per-batch setup and let more docs\nshare the batch-internal Map/Reduce fan-out; smaller batches spread a\nKB's backlog across more concurrent batches (finer scheduling grain).", @@ -32075,12 +32402,16 @@ const docTemplate = `{ "type": "integer" }, "max_pages_per_ingest": { - "description": "MaxPagesPerIngest limits pages created/updated per ingest operation (0 = no limit)", - "type": "integer" + "description": "MaxPagesPerIngest limits pages created or updated per ingest. 0 means no limit.", + "type": "integer", + "maximum": 1000, + "minimum": 0, + "x-agent": "wiki_max_pages" }, "synthesis_model_id": { - "description": "SynthesisModelID is the LLM model ID used for wiki page generation and updates", - "type": "string" + "description": "SynthesisModelID is the model that writes Wiki pages. Empty uses summary_model_id.", + "type": "string", + "x-agent": "wiki_synthesis_model_id" } } }, @@ -33256,6 +33587,25 @@ const docTemplate = `{ } } }, + "internal_handler.CreateTagRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "color": { + "type": "string" + }, + "name": { + "description": "Tag name, unique in this knowledge base", + "type": "string", + "x-agent": true + }, + "sort_order": { + "type": "integer" + } + } + }, "internal_handler.CurrentUserCapabilities": { "type": "object", "properties": { @@ -34009,6 +34359,9 @@ const docTemplate = `{ }, "internal_handler.KnowledgeBaseView": { "type": "object", + "required": [ + "name" + ], "properties": { "asr_config": { "description": "ASR config (Automatic Speech Recognition)", @@ -34016,7 +34369,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "auto_tag_config": { "description": "AutoTagConfig controls asynchronous association of existing tags after parsing.", @@ -34024,7 +34379,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "capabilities": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCapabilities" @@ -34032,7 +34389,8 @@ const docTemplate = `{ "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "chunking_config": { "description": "Chunking configuration", @@ -34040,7 +34398,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "created_at": { "description": "Creation time of the knowledge base", @@ -34068,8 +34428,9 @@ const docTemplate = `{ "x-agent": true }, "embedding_model_id": { - "description": "ID of the embedding model", - "type": "string" + "description": "ID of the embedding model. model.list returns the ids. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" }, "extract_config": { "description": "Extract config", @@ -34077,7 +34438,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "faq_config": { "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", @@ -34085,7 +34448,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "generated_profile": { "description": "GeneratedProfile is the machine-generated description: a gist, merged\ntopics, typical questions and the aggregate snapshot they came from. It\nnever overwrites the user-authored Description; both are shown to agents.", @@ -34098,7 +34463,8 @@ const docTemplate = `{ "id": { "description": "Unique identifier of the knowledge base", "type": "string", - "x-agent": "knowledge_base_id" + "x-agent": "knowledge_base_id", + "x-agent-response": true }, "image_processing_config": { "description": "Image processing configuration", @@ -34106,7 +34472,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "indexing_strategy": { "description": "IndexingStrategy controls which indexing pipelines are active for this knowledge base.\nPipelines: vector search, keyword search, wiki generation, knowledge graph extraction.", @@ -34115,7 +34483,8 @@ const docTemplate = `{ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" } ], - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_pinned": { "description": "IsPinned and PinnedAt are computed per-caller from user_kb_pins\n(see migration 000050). They used to be stored on the row itself,\nwhich made pinning a workspace-wide ordering decision gated behind\nthe kb-edit RBAC guard. The columns are still present in legacy\nschemas for rollback safety but are no longer read or written by\nthe application — both fields are tagged ` + "`" + `gorm:\"-\"` + "`" + ` so GORM\nignores them on every CRUD call and the list handler stamps them\nafter enriching with the caller's pin set.", @@ -34124,7 +34493,8 @@ const docTemplate = `{ "is_processing": { "description": "IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases)", "type": "boolean", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_temporary": { "description": "Whether this knowledge base is temporary (ephemeral) and should be hidden from UI", @@ -34133,7 +34503,8 @@ const docTemplate = `{ "knowledge_count": { "description": "Knowledge count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "my_permission": { "description": "MyPermission is the caller's role on a knowledge base shared from\nanother workspace; GET /knowledge-bases/{id} sets it.", @@ -34148,7 +34519,8 @@ const docTemplate = `{ "name": { "description": "Name of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "pinned_at": { "description": "PinnedAt records when the current caller pinned this knowledge\nbase; nil when they have not.", @@ -34157,7 +34529,8 @@ const docTemplate = `{ "processing_count": { "description": "ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "profile_config": { "description": "ProfileConfig controls automatic generation of the knowledge-base\ndescription from per-document profiles (document knowledge bases only).", @@ -34165,7 +34538,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "question_generation_config": { "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", @@ -34173,7 +34548,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "share_count": { "description": "ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)", @@ -34181,7 +34558,8 @@ const docTemplate = `{ }, "storage_backend_id": { "description": "StorageBackendID binds this KB to one concrete storage instance. The\nlegacy provider field remains readable during migration only.", - "type": "string" + "type": "string", + "x-agent": "storage_backend_id" }, "storage_config": { "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", @@ -34200,29 +34578,37 @@ const docTemplate = `{ ] }, "summary_model_id": { - "description": "Summary model ID", - "type": "string" + "description": "Summary model ID. model.list returns the ids. Used for summaries, and as the default for auto-tagging and the AI description.", + "type": "string", + "x-agent": "summary_model_id" }, "tenant_id": { "description": "Workspace ID", "type": "integer" }, "type": { - "description": "Type of the knowledge base (document, faq, etc.)", + "description": "Type of the knowledge base: document, faq or wiki. Empty means document.", "type": "string", + "enum": [ + "document", + "faq", + "wiki" + ], "x-agent": true }, "updated_at": { "description": "Last updated time of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "vector_store_engine_type": { "type": "string" }, "vector_store_id": { "description": "VectorStoreID references the VectorStore this knowledge base is bound to.\nWhen nil, the KB falls back to the workspace's effective engines derived from\nthe RETRIEVE_DRIVER environment variable (env store flow).\nThis field is set once at creation time and must not be modified afterwards;\nenforcement lives at the GORM layer (` + "`" + `\u003c-:create` + "`" + `) plus the service-layer\nKB update path, which omits this field from its update DTO.", - "type": "string" + "type": "string", + "x-agent": "vector_store_id" }, "vector_store_name": { "type": "string" @@ -34239,7 +34625,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "wiki_config": { "description": "WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases)", @@ -34247,7 +34635,9 @@ const docTemplate = `{ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true } } }, @@ -34352,6 +34742,47 @@ const docTemplate = `{ } } }, + "internal_handler.KnowledgeTagBatchRequest": { + "type": "object", + "properties": { + "kb_id": { + "description": "Knowledge base the documents belong to.", + "type": "string", + "x-agent": "knowledge_base_id", + "x-agent-required": true + }, + "knowledge_ids": { + "description": "Documents that receive the same tags. Mutually exclusive with updates.", + "type": "array", + "items": { + "type": "string" + }, + "x-agent": true, + "x-agent-maximum": "20", + "x-agent-required": true + }, + "tag_ids": { + "description": "Tags to set on every listed document. An empty list clears them.", + "type": "array", + "items": { + "type": "string" + }, + "x-agent": true, + "x-agent-maximum": "50", + "x-agent-required": true + }, + "updates": { + "description": "Map of knowledge id to the tag ids that replace its current tags.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, "internal_handler.ListAgentsResponse": { "type": "object", "properties": { @@ -35007,6 +35438,124 @@ const docTemplate = `{ } } }, + "internal_handler.PatchKnowledgeBaseRequest": { + "type": "object", + "properties": { + "asr_config": { + "description": "Speech transcription.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" + } + ] + }, + "auto_tag_config": { + "description": "Automatic tagging.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" + } + ] + }, + "chunking_config": { + "description": "Chunking settings. Only the fields present are changed.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + } + ] + }, + "description": { + "description": "New description. Omit to keep it; an empty string clears it.", + "type": "string", + "x-agent": true + }, + "embedding_model_id": { + "description": "Embedding model. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" + }, + "extract_config": { + "description": "Graph extraction. Node types stay in the knowledge base editor.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + } + ] + }, + "faq_config": { + "description": "FAQ indexing. Only for an FAQ knowledge base.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + } + ] + }, + "image_processing_config": { + "description": "Image description settings.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + } + ] + }, + "indexing_strategy": { + "description": "Indexing pipelines. A flag left out stays as it is.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" + } + ] + }, + "name": { + "description": "New name. Omit to keep the current one.", + "type": "string", + "x-agent": true + }, + "profile_config": { + "description": "AI description of the knowledge base.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" + } + ] + }, + "question_generation_config": { + "description": "Generated questions for each chunk.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + } + ] + }, + "storage_backend_id": { + "description": "Storage instance to bind. Omit to keep the current one.", + "type": "string", + "x-agent": "storage_backend_id" + }, + "summary_model_id": { + "description": "Summary model. model.list returns the ids.", + "type": "string", + "x-agent": "summary_model_id" + }, + "vlm_config": { + "description": "Image captions.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" + } + ] + }, + "wiki_config": { + "description": "Wiki page settings.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" + } + ] + } + } + }, "internal_handler.PlaceholderGroups": { "type": "object", "properties": { @@ -36158,6 +36707,22 @@ const docTemplate = `{ } } }, + "internal_handler.UpdateTagRequest": { + "type": "object", + "properties": { + "color": { + "type": "string" + }, + "name": { + "description": "New name. Omit to keep the current one.", + "type": "string", + "x-agent": true + }, + "sort_order": { + "type": "integer" + } + } + }, "internal_handler.ValidateTokenResponse": { "type": "object", "properties": { diff --git a/docs/swagger.json b/docs/swagger.json index 24009449..ba56a2d5 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -4394,7 +4394,13 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.create", + "label_param": "name", + "risk": "write" + }, + "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." } }, "/knowledge-bases/copy": { @@ -4714,6 +4720,7 @@ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -4745,7 +4752,99 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.delete", + "label": "name", + "risk": "destructive", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Deletes the knowledge base and every document in it. Cannot be undone. Only the owner can delete it." + }, + "patch": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "修改请求里出现的设置。未出现的字段保持不变,包括分块、索引和模型里没写到的项。", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "知识库" + ], + "summary": "部分更新知识库", + "parameters": [ + { + "type": "string", + "x-agent": "knowledge_base_id", + "description": "知识库ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "要修改的字段", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/internal_handler.PatchKnowledgeBaseRequest" + } + } + ], + "responses": { + "200": { + "description": "更新后的知识库", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/internal_handler.DataResponse" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/internal_handler.KnowledgeBaseView" + } + } + } + ] + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "403": { + "description": "无权限", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "404": { + "description": "知识库不存在", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + }, + "x-agent": { + "id": "knowledge_base.update", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge-bases/{id}/activity": { @@ -6768,7 +6867,7 @@ "risk": "write", "target": "knowledge_base.get" }, - "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." } }, "/knowledge-bases/{id}/knowledge/url": { @@ -7390,6 +7489,7 @@ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7401,18 +7501,7 @@ "in": "body", "required": true, "schema": { - "type": "object", - "properties": { - "color": { - "type": "string" - }, - "name": { - "type": "string" - }, - "sort_order": { - "type": "integer" - } - } + "$ref": "#/definitions/internal_handler.CreateTagRequest" } } ], @@ -7441,7 +7530,14 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.create_tag", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Creates a tag in the knowledge base. Pass the returned tag id to knowledge.set_tags." } }, "/knowledge-bases/{id}/tags/{tag_id}": { @@ -7468,6 +7564,7 @@ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7475,6 +7572,7 @@ }, { "type": "string", + "x-agent": "tag_id", "description": "标签ID (UUID或seq_id)", "name": "tag_id", "in": "path", @@ -7486,7 +7584,7 @@ "in": "body", "required": true, "schema": { - "type": "object" + "$ref": "#/definitions/internal_handler.UpdateTagRequest" } } ], @@ -7515,7 +7613,14 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.update_tag", + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "x-agent-hint": "Renames a tag. tag_id comes from knowledge_base.list_tags. A field left out is kept." }, "delete": { "security": [ @@ -7540,6 +7645,7 @@ "parameters": [ { "type": "string", + "x-agent": "knowledge_base_id", "description": "知识库ID", "name": "id", "in": "path", @@ -7547,6 +7653,7 @@ }, { "type": "string", + "x-agent": "tag_id", "description": "标签ID (UUID或seq_id)", "name": "tag_id", "in": "path", @@ -7586,7 +7693,14 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge_base.delete_tag", + "label": "name", + "risk": "destructive", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge-chat/{session_id}": { @@ -8084,6 +8198,7 @@ "parameters": [ { "type": "string", + "x-agent": "knowledge_id", "description": "知识ID", "name": "id", "in": "path", @@ -8124,7 +8239,14 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge.update_manual", + "label": "title", + "risk": "write", + "target": "knowledge.get" + }, + "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." } }, "/knowledge/move": { @@ -8348,7 +8470,7 @@ "ApiKeyAuth": [] } ], - "description": "批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析", + "description": "批量更新知识条目的标签。传 updates,或传 knowledge_ids 与 tag_ids。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析", "consumes": [ "application/json" ], @@ -8361,12 +8483,12 @@ "summary": "批量更新知识标签", "parameters": [ { - "description": "标签更新请求(updates 必填,kb_id 可选)", + "description": "标签更新请求", "name": "request", "in": "body", "required": true, "schema": { - "type": "object" + "$ref": "#/definitions/internal_handler.KnowledgeTagBatchRequest" } } ], @@ -8383,7 +8505,20 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" } } - } + }, + "x-agent": { + "id": "knowledge.set_tags", + "items": { + "as": "knowledge_id", + "label": "title", + "param": "knowledge_ids", + "target": "knowledge.get" + }, + "label": "name", + "risk": "write", + "target": "knowledge_base.get" + }, + "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." } }, "/knowledge/{id}": { @@ -22883,14 +23018,19 @@ "type": "object", "properties": { "enabled": { - "type": "boolean" + "description": "Enabled turns speech transcription on. Also send asr_model_id.", + "type": "boolean", + "x-agent": "asr_enabled" }, "language": { - "description": "optional: language hint for transcription", - "type": "string" + "description": "Language is an optional hint for transcription, such as zh or en.", + "type": "string", + "x-agent": "asr_language" }, "model_id": { - "type": "string" + "description": "Model that transcribes audio. model.list returns the ids.", + "type": "string", + "x-agent": "asr_model_id" } } }, @@ -23392,17 +23532,26 @@ "type": "object", "properties": { "enabled": { - "type": "boolean" + "description": "Enabled turns automatic tagging on. The model picks from tags that already exist.", + "type": "boolean", + "x-agent": "auto_tag_enabled" }, "max_tags": { - "type": "integer" + "description": "MaxTags is how many tags one document may receive, from 1 to 10.", + "type": "integer", + "maximum": 10, + "minimum": 1, + "x-agent": "auto_tag_max_tags" }, "model_id": { - "type": "string" + "description": "ModelID overrides the summary model. Empty uses summary_model_id.", + "type": "string", + "x-agent": "auto_tag_model_id" }, "skip_if_tagged": { - "description": "SkipIfTagged leaves documents that already carry tags untouched, so a\ndeliberate manual classification is not diluted by model guesses. It is\na pointer because the default is true: rows written before this field\nexisted decode to nil and must not silently flip to \"always append\".", - "type": "boolean" + "description": "SkipIfTagged leaves a document alone when it already has tags. Empty means yes.", + "type": "boolean", + "x-agent": "auto_tag_skip_if_tagged" } } }, @@ -23783,30 +23932,45 @@ "properties": { "child_chunk_size": { "description": "ChildChunkSize is the size of child chunks used for embedding (default: 384).\nOnly used when EnableParentChild is true.", - "type": "integer" + "type": "integer", + "maximum": 10000, + "minimum": 1, + "x-agent": true }, "chunk_overlap": { - "description": "Chunk overlap", - "type": "integer" + "description": "Chunk overlap in characters.", + "type": "integer", + "maximum": 5000, + "minimum": 0, + "x-agent": true }, "chunk_size": { - "description": "Chunk size", - "type": "integer" + "description": "Chunk size in characters. Empty on create uses the server default.", + "type": "integer", + "maximum": 10000, + "minimum": 100, + "x-agent": true }, "enable_parent_child": { - "description": "EnableParentChild enables two-level parent-child chunking strategy.\nWhen enabled, large parent chunks provide context while small child chunks\nare used for vector matching. Retrieval matches on child but returns parent content.", - "type": "boolean" + "description": "EnableParentChild splits into large parent chunks and small child chunks. Search matches a child and returns its parent.", + "type": "boolean", + "x-agent": true }, "languages": { - "description": "Languages hints the heuristic patterns. Empty = auto-detect from content.\nExamples: [\"de\"], [\"en\", \"zh\"].", + "description": "Languages hints the splitter, for example de or zh. Empty detects the language from the document.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": true, + "x-agent-maximum": "20" }, "parent_chunk_size": { "description": "ParentChunkSize is the size of parent chunks (default: 4096).\nOnly used when EnableParentChild is true.", - "type": "integer" + "type": "integer", + "maximum": 20000, + "minimum": 1, + "x-agent": true }, "parser_engine_rules": { "description": "ParserEngineRules configures which parser engine to use for each file type.\nWhen empty, DefaultParserEngine is used (builtin/simple routing, except\ntypes that only a specific engine can parse: ppt/pptx fall back to\nmarkitdown). A linked anydoc binding is preferred for every type it\nconverts.", @@ -23816,23 +23980,39 @@ } }, "separators": { - "description": "Separators", + "description": "Separators, in the order they are tried.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": true, + "x-agent-maximum": "20" }, "strategy": { - "description": "Strategy selects the adaptive chunking tier. Empty / \"legacy\" preserves\nthe historical recursive splitter; \"auto\" lets a profiler pick between\nheading-aware, heuristic and recursive tiers; \"heading\" / \"heuristic\" /\n\"recursive\" pin the tier explicitly.", - "type": "string" + "description": "Strategy selects how documents are split: auto, heading, heuristic, recursive or legacy. Empty keeps the server default.", + "type": "string", + "enum": [ + "auto", + "heading", + "heuristic", + "recursive", + "legacy" + ], + "x-agent": true }, "table_metadata_instructions": { - "description": "TableMetadataInstructions contains optional business guidance used when\ngenerating searchable summaries for CSV/Excel tables. The system-owned\noutput contract remains fixed; these instructions only add domain context.", - "type": "string" + "description": "TableMetadataInstructions is extra guidance for CSV and Excel summaries. The output format stays fixed.", + "type": "string", + "x-agent": true, + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "token_limit": { - "description": "TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize\nas a character count.", - "type": "integer" + "description": "TokenLimit caps chunk size in approximate tokens. 0 uses ChunkSize as a character count.", + "type": "integer", + "maximum": 100000, + "minimum": 0, + "x-agent": true } } }, @@ -24725,11 +24905,16 @@ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions adds domain-specific extraction guidance while the\nsystem keeps ownership of the structured graph output protocol.", - "type": "string" + "description": "CustomInstructions adds domain guidance. The graph output format stays fixed.", + "type": "string", + "x-agent": "extract_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns graph extraction on. Node and relation types are edited in the knowledge base editor.", + "type": "boolean", + "x-agent": "extract_enabled" }, "nodes": { "type": "array", @@ -24744,13 +24929,20 @@ } }, "tags": { + "description": "Tags are the entity labels extraction may use.", "type": "array", "items": { "type": "string" - } + }, + "x-agent": "extract_tags", + "x-agent-maximum": "50" }, "text": { - "type": "string" + "description": "Text is the extraction prompt. Required when extraction is on and no text is saved yet.", + "type": "string", + "x-agent": "extract_text", + "x-agent-detail": true, + "x-agent-max-bytes": "8000" } } }, @@ -24790,10 +24982,30 @@ "type": "object", "properties": { "index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + "description": "IndexMode is question_only or question_answer.", + "enum": [ + "question_only", + "question_answer" + ], + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + } + ], + "x-agent": "faq_index_mode" }, "question_index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + "description": "QuestionIndexMode is combined or separate.", + "enum": [ + "combined", + "separate" + ], + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + } + ], + "x-agent": "faq_question_index_mode" } } }, @@ -25615,15 +25827,18 @@ }, "image_attrs_enabled": { "description": "ImageAttrsEnabled turns the attribute-observed image pipeline on for this\nknowledge base. It is off by default on purpose, so upgrading an\nexisting deployment never changes what happens to documents already\nbeing ingested: with it off every image is described and OCR'd exactly\nas before. When on, the describe round also observes image attributes and\nthe attribute policy decides whether OCR runs for it. A single upload can\noverride it per document through\nKnowledgeProcessOverrides.ImageAttrsEnabled.", - "type": "boolean" + "type": "boolean", + "x-agent": true }, "image_vector_enabled": { "description": "ImageVectorEnabled lets a knowledge base whose embedding model takes\nimages index each image by its own vector and recall it with one. It\nis off by default on purpose: a model that takes images is also used\nfor plain text, and turning this on costs an embedding call per image\nand widens vector recall. Existing knowledge bases stay off after an\nupgrade because the stored JSON has no such key.", - "type": "boolean" + "type": "boolean", + "x-agent": true }, "model_id": { - "description": "Model ID", - "type": "string" + "description": "Model ID used when describing images. Empty uses the knowledge base's caption model.", + "type": "string", + "x-agent": "image_model_id" } } }, @@ -26133,6 +26348,9 @@ }, "github_com_Tencent_WeKnora_internal_types.KnowledgeBase": { "type": "object", + "required": [ + "name" + ], "properties": { "asr_config": { "description": "ASR config (Automatic Speech Recognition)", @@ -26140,7 +26358,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "auto_tag_config": { "description": "AutoTagConfig controls asynchronous association of existing tags after parsing.", @@ -26148,12 +26368,15 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "chunking_config": { "description": "Chunking configuration", @@ -26161,7 +26384,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "created_at": { "description": "Creation time of the knowledge base", @@ -26189,8 +26414,9 @@ "x-agent": true }, "embedding_model_id": { - "description": "ID of the embedding model", - "type": "string" + "description": "ID of the embedding model. model.list returns the ids. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" }, "extract_config": { "description": "Extract config", @@ -26198,7 +26424,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "faq_config": { "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", @@ -26206,7 +26434,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "generated_profile": { "description": "GeneratedProfile is the machine-generated description: a gist, merged\ntopics, typical questions and the aggregate snapshot they came from. It\nnever overwrites the user-authored Description; both are shown to agents.", @@ -26219,7 +26449,8 @@ "id": { "description": "Unique identifier of the knowledge base", "type": "string", - "x-agent": "knowledge_base_id" + "x-agent": "knowledge_base_id", + "x-agent-response": true }, "image_processing_config": { "description": "Image processing configuration", @@ -26227,7 +26458,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "indexing_strategy": { "description": "IndexingStrategy controls which indexing pipelines are active for this knowledge base.\nPipelines: vector search, keyword search, wiki generation, knowledge graph extraction.", @@ -26236,7 +26469,8 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" } ], - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_pinned": { "description": "IsPinned and PinnedAt are computed per-caller from user_kb_pins\n(see migration 000050). They used to be stored on the row itself,\nwhich made pinning a workspace-wide ordering decision gated behind\nthe kb-edit RBAC guard. The columns are still present in legacy\nschemas for rollback safety but are no longer read or written by\nthe application — both fields are tagged `gorm:\"-\"` so GORM\nignores them on every CRUD call and the list handler stamps them\nafter enriching with the caller's pin set.", @@ -26245,7 +26479,8 @@ "is_processing": { "description": "IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases)", "type": "boolean", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_temporary": { "description": "Whether this knowledge base is temporary (ephemeral) and should be hidden from UI", @@ -26254,12 +26489,14 @@ "knowledge_count": { "description": "Knowledge count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "name": { "description": "Name of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "pinned_at": { "description": "PinnedAt records when the current caller pinned this knowledge\nbase; nil when they have not.", @@ -26268,7 +26505,8 @@ "processing_count": { "description": "ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "profile_config": { "description": "ProfileConfig controls automatic generation of the knowledge-base\ndescription from per-document profiles (document knowledge bases only).", @@ -26276,7 +26514,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "question_generation_config": { "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", @@ -26284,7 +26524,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "share_count": { "description": "ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)", @@ -26292,7 +26534,8 @@ }, "storage_backend_id": { "description": "StorageBackendID binds this KB to one concrete storage instance. The\nlegacy provider field remains readable during migration only.", - "type": "string" + "type": "string", + "x-agent": "storage_backend_id" }, "storage_config": { "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", @@ -26311,26 +26554,34 @@ ] }, "summary_model_id": { - "description": "Summary model ID", - "type": "string" + "description": "Summary model ID. model.list returns the ids. Used for summaries, and as the default for auto-tagging and the AI description.", + "type": "string", + "x-agent": "summary_model_id" }, "tenant_id": { "description": "Workspace ID", "type": "integer" }, "type": { - "description": "Type of the knowledge base (document, faq, etc.)", + "description": "Type of the knowledge base: document, faq or wiki. Empty means document.", "type": "string", + "enum": [ + "document", + "faq", + "wiki" + ], "x-agent": true }, "updated_at": { "description": "Last updated time of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "vector_store_id": { "description": "VectorStoreID references the VectorStore this knowledge base is bound to.\nWhen nil, the KB falls back to the workspace's effective engines derived from\nthe RETRIEVE_DRIVER environment variable (env store flow).\nThis field is set once at creation time and must not be modified afterwards;\nenforcement lives at the GORM layer (`\u003c-:create`) plus the service-layer\nKB update path, which omits this field from its update DTO.", - "type": "string" + "type": "string", + "x-agent": "vector_store_id" }, "vlm_config": { "description": "VLM config", @@ -26338,7 +26589,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "wiki_config": { "description": "WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases)", @@ -26346,13 +26599,23 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true } } }, "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig": { "type": "object", "properties": { + "asr_config": { + "description": "ASRConfig replaces speech-recognition settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" + } + ] + }, "auto_tag_config": { "description": "AutoTagConfig controls optional automatic association of existing KB tags.", "allOf": [ @@ -26369,6 +26632,18 @@ } ] }, + "embedding_model_id": { + "description": "EmbeddingModelID changes the embedding model. nil means no change.\nA knowledge base that already has documents cannot switch models.", + "type": "string" + }, + "extract_config": { + "description": "ExtractConfig replaces graph extraction settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + } + ] + }, "faq_config": { "description": "FAQ configuration (only for FAQ type knowledge bases)", "allOf": [ @@ -26401,6 +26676,22 @@ } ] }, + "question_generation_config": { + "description": "QuestionGenerationConfig replaces generated-question settings when set. nil means no change.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + } + ] + }, + "storage_backend_id": { + "description": "StorageBackendID rebinds file storage. nil means no change.", + "type": "string" + }, + "summary_model_id": { + "description": "SummaryModelID changes the summary model. nil means no change.", + "type": "string" + }, "wiki_config": { "description": "Wiki configuration (only for wiki-enabled knowledge bases)", "allOf": [ @@ -26472,15 +26763,21 @@ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions is appended to the stable system prompt, e.g. the\naudience the description should address or terms to keep.", - "type": "string" + "description": "CustomInstructions is extra guidance for the description, such as the audience. The format stays fixed.", + "type": "string", + "x-agent": "profile_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns the AI knowledge-base description on.", + "type": "boolean", + "x-agent": "profile_enabled" }, "model_id": { - "description": "ModelID overrides the chat model; empty falls back to the KB summary model.", - "type": "string" + "description": "ModelID overrides the summary model. Empty uses summary_model_id.", + "type": "string", + "x-agent": "profile_model_id" } } }, @@ -27346,7 +27643,8 @@ "description": "Markdown content. The assistant may send a full document; the API limit\nis 200000 runes, and x-agent-max-bytes covers that in UTF-8.", "type": "string", "x-agent": true, - "x-agent-max-bytes": "800000" + "x-agent-max-bytes": "800000", + "x-agent-required": true }, "process_config": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeProcessOverrides" @@ -27358,7 +27656,8 @@ "draft", "publish" ], - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "tag_ids": { "type": "array", @@ -29110,15 +29409,23 @@ "type": "object", "properties": { "custom_instructions": { - "description": "CustomInstructions describes the intended audience or question style.\nIt is appended to the stable system question-generation template.", - "type": "string" + "description": "CustomInstructions describes who the questions are for. The question format stays fixed.", + "type": "string", + "x-agent": "question_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "enabled": { - "type": "boolean" + "description": "Enabled turns question generation on. Generated questions are indexed beside the chunk.", + "type": "boolean", + "x-agent": "question_generation_enabled" }, "question_count": { - "description": "Number of questions to generate per chunk (default: 3, max: 10)", - "type": "integer" + "description": "QuestionCount is how many questions to write per chunk, from 1 to 10.", + "type": "integer", + "maximum": 10, + "minimum": 1, + "x-agent": "question_count" } } }, @@ -31567,22 +31874,30 @@ "type": "string" }, "custom_instructions": { - "description": "CustomInstructions adds KB-specific image interpretation guidance without\nreplacing the system-owned OCR and Markdown output contract.", - "type": "string" + "description": "CustomInstructions adds image-reading guidance. The OCR and Markdown format stay fixed.", + "type": "string", + "x-agent": "vlm_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "description_language": { - "description": "DescriptionLanguage controls the language used for generated image\ncaptions. Empty means follow the document/request language.", - "type": "string" + "description": "DescriptionLanguage is the language of generated image captions. Empty follows the document language.", + "type": "string", + "x-agent": "vlm_language" }, "enabled": { - "type": "boolean" + "description": "Enabled turns image captions on. Also send vlm_model_id.", + "type": "boolean", + "x-agent": "vlm_enabled" }, "interface_type": { "description": "Interface Type: \"ollama\" or \"openai\"", "type": "string" }, "model_id": { - "type": "string" + "description": "Model that writes image captions. model.list returns the ids.", + "type": "string", + "x-agent": "vlm_model_id" }, "model_name": { "description": "兼容老版本\nModel Name", @@ -32036,20 +32351,32 @@ "type": "object", "properties": { "content_instructions": { - "description": "ContentInstructions controls tone, structure and emphasis for generated\nsummary/entity/index prose. Citation and merge rules remain system-owned.", - "type": "string" + "description": "ContentInstructions sets tone and emphasis for generated Wiki prose. Citations stay fixed.", + "type": "string", + "x-agent": "wiki_content_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "extraction_granularity": { - "description": "ExtractionGranularity controls how many candidate slugs Pass 0 extracts\nper document. Empty / unknown value is treated as WikiExtractionStandard.", + "description": "ExtractionGranularity is focused, standard or exhaustive. Empty means standard.", + "enum": [ + "focused", + "standard", + "exhaustive" + ], "allOf": [ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiExtractionGranularity" } - ] + ], + "x-agent": "wiki_granularity" }, "extraction_instructions": { - "description": "ExtractionInstructions tells candidate extraction which domain concepts\nto emphasize without replacing the stable JSON/citation protocol.", - "type": "string" + "description": "ExtractionInstructions tells page extraction which concepts to keep. The output format stays fixed.", + "type": "string", + "x-agent": "wiki_extraction_instructions", + "x-agent-detail": true, + "x-agent-max-bytes": "4000" }, "ingest_batch_size": { "description": "IngestBatchSize controls how many pending ops a single batch claims and\nprocesses before scheduling a follow-up. 0 falls back to the hard-coded\ndefault (5). Larger batches amortize per-batch setup and let more docs\nshare the batch-internal Map/Reduce fan-out; smaller batches spread a\nKB's backlog across more concurrent batches (finer scheduling grain).", @@ -32068,12 +32395,16 @@ "type": "integer" }, "max_pages_per_ingest": { - "description": "MaxPagesPerIngest limits pages created/updated per ingest operation (0 = no limit)", - "type": "integer" + "description": "MaxPagesPerIngest limits pages created or updated per ingest. 0 means no limit.", + "type": "integer", + "maximum": 1000, + "minimum": 0, + "x-agent": "wiki_max_pages" }, "synthesis_model_id": { - "description": "SynthesisModelID is the LLM model ID used for wiki page generation and updates", - "type": "string" + "description": "SynthesisModelID is the model that writes Wiki pages. Empty uses summary_model_id.", + "type": "string", + "x-agent": "wiki_synthesis_model_id" } } }, @@ -33249,6 +33580,25 @@ } } }, + "internal_handler.CreateTagRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "color": { + "type": "string" + }, + "name": { + "description": "Tag name, unique in this knowledge base", + "type": "string", + "x-agent": true + }, + "sort_order": { + "type": "integer" + } + } + }, "internal_handler.CurrentUserCapabilities": { "type": "object", "properties": { @@ -34002,6 +34352,9 @@ }, "internal_handler.KnowledgeBaseView": { "type": "object", + "required": [ + "name" + ], "properties": { "asr_config": { "description": "ASR config (Automatic Speech Recognition)", @@ -34009,7 +34362,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "auto_tag_config": { "description": "AutoTagConfig controls asynchronous association of existing tags after parsing.", @@ -34017,7 +34372,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "capabilities": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCapabilities" @@ -34025,7 +34382,8 @@ "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "chunking_config": { "description": "Chunking configuration", @@ -34033,7 +34391,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "created_at": { "description": "Creation time of the knowledge base", @@ -34061,8 +34421,9 @@ "x-agent": true }, "embedding_model_id": { - "description": "ID of the embedding model", - "type": "string" + "description": "ID of the embedding model. model.list returns the ids. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" }, "extract_config": { "description": "Extract config", @@ -34070,7 +34431,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "faq_config": { "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", @@ -34078,7 +34441,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "generated_profile": { "description": "GeneratedProfile is the machine-generated description: a gist, merged\ntopics, typical questions and the aggregate snapshot they came from. It\nnever overwrites the user-authored Description; both are shown to agents.", @@ -34091,7 +34456,8 @@ "id": { "description": "Unique identifier of the knowledge base", "type": "string", - "x-agent": "knowledge_base_id" + "x-agent": "knowledge_base_id", + "x-agent-response": true }, "image_processing_config": { "description": "Image processing configuration", @@ -34099,7 +34465,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "indexing_strategy": { "description": "IndexingStrategy controls which indexing pipelines are active for this knowledge base.\nPipelines: vector search, keyword search, wiki generation, knowledge graph extraction.", @@ -34108,7 +34476,8 @@ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" } ], - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_pinned": { "description": "IsPinned and PinnedAt are computed per-caller from user_kb_pins\n(see migration 000050). They used to be stored on the row itself,\nwhich made pinning a workspace-wide ordering decision gated behind\nthe kb-edit RBAC guard. The columns are still present in legacy\nschemas for rollback safety but are no longer read or written by\nthe application — both fields are tagged `gorm:\"-\"` so GORM\nignores them on every CRUD call and the list handler stamps them\nafter enriching with the caller's pin set.", @@ -34117,7 +34486,8 @@ "is_processing": { "description": "IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases)", "type": "boolean", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "is_temporary": { "description": "Whether this knowledge base is temporary (ephemeral) and should be hidden from UI", @@ -34126,7 +34496,8 @@ "knowledge_count": { "description": "Knowledge count (not stored in database, calculated on query)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "my_permission": { "description": "MyPermission is the caller's role on a knowledge base shared from\nanother workspace; GET /knowledge-bases/{id} sets it.", @@ -34141,7 +34512,8 @@ "name": { "description": "Name of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-required": true }, "pinned_at": { "description": "PinnedAt records when the current caller pinned this knowledge\nbase; nil when they have not.", @@ -34150,7 +34522,8 @@ "processing_count": { "description": "ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases)", "type": "integer", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "profile_config": { "description": "ProfileConfig controls automatic generation of the knowledge-base\ndescription from per-document profiles (document knowledge bases only).", @@ -34158,7 +34531,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "question_generation_config": { "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", @@ -34166,7 +34541,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "share_count": { "description": "ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database)", @@ -34174,7 +34551,8 @@ }, "storage_backend_id": { "description": "StorageBackendID binds this KB to one concrete storage instance. The\nlegacy provider field remains readable during migration only.", - "type": "string" + "type": "string", + "x-agent": "storage_backend_id" }, "storage_config": { "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", @@ -34193,29 +34571,37 @@ ] }, "summary_model_id": { - "description": "Summary model ID", - "type": "string" + "description": "Summary model ID. model.list returns the ids. Used for summaries, and as the default for auto-tagging and the AI description.", + "type": "string", + "x-agent": "summary_model_id" }, "tenant_id": { "description": "Workspace ID", "type": "integer" }, "type": { - "description": "Type of the knowledge base (document, faq, etc.)", + "description": "Type of the knowledge base: document, faq or wiki. Empty means document.", "type": "string", + "enum": [ + "document", + "faq", + "wiki" + ], "x-agent": true }, "updated_at": { "description": "Last updated time of the knowledge base", "type": "string", - "x-agent": true + "x-agent": true, + "x-agent-response": true }, "vector_store_engine_type": { "type": "string" }, "vector_store_id": { "description": "VectorStoreID references the VectorStore this knowledge base is bound to.\nWhen nil, the KB falls back to the workspace's effective engines derived from\nthe RETRIEVE_DRIVER environment variable (env store flow).\nThis field is set once at creation time and must not be modified afterwards;\nenforcement lives at the GORM layer (`\u003c-:create`) plus the service-layer\nKB update path, which omits this field from its update DTO.", - "type": "string" + "type": "string", + "x-agent": "vector_store_id" }, "vector_store_name": { "type": "string" @@ -34232,7 +34618,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true }, "wiki_config": { "description": "WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases)", @@ -34240,7 +34628,9 @@ { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" } - ] + ], + "x-agent": true, + "x-agent-detail": true } } }, @@ -34345,6 +34735,47 @@ } } }, + "internal_handler.KnowledgeTagBatchRequest": { + "type": "object", + "properties": { + "kb_id": { + "description": "Knowledge base the documents belong to.", + "type": "string", + "x-agent": "knowledge_base_id", + "x-agent-required": true + }, + "knowledge_ids": { + "description": "Documents that receive the same tags. Mutually exclusive with updates.", + "type": "array", + "items": { + "type": "string" + }, + "x-agent": true, + "x-agent-maximum": "20", + "x-agent-required": true + }, + "tag_ids": { + "description": "Tags to set on every listed document. An empty list clears them.", + "type": "array", + "items": { + "type": "string" + }, + "x-agent": true, + "x-agent-maximum": "50", + "x-agent-required": true + }, + "updates": { + "description": "Map of knowledge id to the tag ids that replace its current tags.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, "internal_handler.ListAgentsResponse": { "type": "object", "properties": { @@ -35000,6 +35431,124 @@ } } }, + "internal_handler.PatchKnowledgeBaseRequest": { + "type": "object", + "properties": { + "asr_config": { + "description": "Speech transcription.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig" + } + ] + }, + "auto_tag_config": { + "description": "Automatic tagging.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig" + } + ] + }, + "chunking_config": { + "description": "Chunking settings. Only the fields present are changed.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + } + ] + }, + "description": { + "description": "New description. Omit to keep it; an empty string clears it.", + "type": "string", + "x-agent": true + }, + "embedding_model_id": { + "description": "Embedding model. Cannot change after the knowledge base has documents.", + "type": "string", + "x-agent": "embedding_model_id" + }, + "extract_config": { + "description": "Graph extraction. Node types stay in the knowledge base editor.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + } + ] + }, + "faq_config": { + "description": "FAQ indexing. Only for an FAQ knowledge base.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + } + ] + }, + "image_processing_config": { + "description": "Image description settings.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + } + ] + }, + "indexing_strategy": { + "description": "Indexing pipelines. A flag left out stays as it is.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy" + } + ] + }, + "name": { + "description": "New name. Omit to keep the current one.", + "type": "string", + "x-agent": true + }, + "profile_config": { + "description": "AI description of the knowledge base.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig" + } + ] + }, + "question_generation_config": { + "description": "Generated questions for each chunk.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + } + ] + }, + "storage_backend_id": { + "description": "Storage instance to bind. Omit to keep the current one.", + "type": "string", + "x-agent": "storage_backend_id" + }, + "summary_model_id": { + "description": "Summary model. model.list returns the ids.", + "type": "string", + "x-agent": "summary_model_id" + }, + "vlm_config": { + "description": "Image captions.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" + } + ] + }, + "wiki_config": { + "description": "Wiki page settings.", + "allOf": [ + { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig" + } + ] + } + } + }, "internal_handler.PlaceholderGroups": { "type": "object", "properties": { @@ -36151,6 +36700,22 @@ } } }, + "internal_handler.UpdateTagRequest": { + "type": "object", + "properties": { + "color": { + "type": "string" + }, + "name": { + "description": "New name. Omit to keep the current one.", + "type": "string", + "x-agent": true + }, + "sort_order": { + "type": "integer" + } + } + }, "internal_handler.ValidateTokenResponse": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 5e66b40e..f97ca57c 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1089,12 +1089,18 @@ definitions: github_com_Tencent_WeKnora_internal_types.ASRConfig: properties: enabled: + description: Enabled turns speech transcription on. Also send asr_model_id. type: boolean + x-agent: asr_enabled language: - description: 'optional: language hint for transcription' + description: Language is an optional hint for transcription, such as zh or + en. type: string + x-agent: asr_language model_id: + description: Model that transcribes audio. model.list returns the ids. type: string + x-agent: asr_model_id type: object github_com_Tencent_WeKnora_internal_types.AdminCreateUserRequest: properties: @@ -1499,18 +1505,26 @@ definitions: github_com_Tencent_WeKnora_internal_types.AutoTagConfig: properties: enabled: + description: Enabled turns automatic tagging on. The model picks from tags + that already exist. type: boolean + x-agent: auto_tag_enabled max_tags: + description: MaxTags is how many tags one document may receive, from 1 to + 10. + maximum: 10 + minimum: 1 type: integer + x-agent: auto_tag_max_tags model_id: + description: ModelID overrides the summary model. Empty uses summary_model_id. type: string + x-agent: auto_tag_model_id skip_if_tagged: - description: |- - 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". + description: SkipIfTagged leaves a document alone when it already has tags. + Empty means yes. type: boolean + x-agent: auto_tag_skip_if_tagged type: object github_com_Tencent_WeKnora_internal_types.COSEngineConfig: properties: @@ -1806,31 +1820,43 @@ definitions: description: |- ChildChunkSize is the size of child chunks used for embedding (default: 384). Only used when EnableParentChild is true. + maximum: 10000 + minimum: 1 type: integer + x-agent: true chunk_overlap: - description: Chunk overlap + description: Chunk overlap in characters. + maximum: 5000 + minimum: 0 type: integer + x-agent: true chunk_size: - description: Chunk size + description: Chunk size in characters. Empty on create uses the server default. + maximum: 10000 + minimum: 100 type: integer + x-agent: true enable_parent_child: - description: |- - 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. + description: EnableParentChild splits into large parent chunks and small child + chunks. Search matches a child and returns its parent. type: boolean + x-agent: true languages: - description: |- - Languages hints the heuristic patterns. Empty = auto-detect from content. - Examples: ["de"], ["en", "zh"]. + description: Languages hints the splitter, for example de or zh. Empty detects + the language from the document. items: type: string type: array + x-agent: true + x-agent-maximum: "20" parent_chunk_size: description: |- ParentChunkSize is the size of parent chunks (default: 4096). Only used when EnableParentChild is true. + maximum: 20000 + minimum: 1 type: integer + x-agent: true parser_engine_rules: description: |- ParserEngineRules configures which parser engine to use for each file type. @@ -1842,28 +1868,37 @@ definitions: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule' type: array separators: - description: Separators + description: Separators, in the order they are tried. items: type: string type: array + x-agent: true + x-agent-maximum: "20" strategy: - description: |- - 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. + description: 'Strategy selects how documents are split: auto, heading, heuristic, + recursive or legacy. Empty keeps the server default.' + enum: + - auto + - heading + - heuristic + - recursive + - legacy type: string + x-agent: true table_metadata_instructions: - description: |- - 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. + description: TableMetadataInstructions is extra guidance for CSV and Excel + summaries. The output format stays fixed. type: string + x-agent: true + x-agent-detail: true + x-agent-max-bytes: "4000" token_limit: - description: |- - TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize + description: TokenLimit caps chunk size in approximate tokens. 0 uses ChunkSize as a character count. + maximum: 100000 + minimum: 0 type: integer + x-agent: true type: object github_com_Tencent_WeKnora_internal_types.ConnectionConfig: properties: @@ -2673,12 +2708,17 @@ definitions: github_com_Tencent_WeKnora_internal_types.ExtractConfig: properties: custom_instructions: - description: |- - CustomInstructions adds domain-specific extraction guidance while the - system keeps ownership of the structured graph output protocol. + description: CustomInstructions adds domain guidance. The graph output format + stays fixed. type: string + x-agent: extract_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" enabled: + description: Enabled turns graph extraction on. Node and relation types are + edited in the knowledge base editor. type: boolean + x-agent: extract_enabled nodes: items: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode' @@ -2688,11 +2728,19 @@ definitions: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation' type: array tags: + description: Tags are the entity labels extraction may use. items: type: string type: array + x-agent: extract_tags + x-agent-maximum: "50" text: + description: Text is the extraction prompt. Required when extraction is on + and no text is saved yet. type: string + x-agent: extract_text + x-agent-detail: true + x-agent-max-bytes: "8000" type: object github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload: properties: @@ -2719,9 +2767,21 @@ definitions: github_com_Tencent_WeKnora_internal_types.FAQConfig: properties: index_mode: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode' + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode' + description: IndexMode is question_only or question_answer. + enum: + - question_only + - question_answer + x-agent: faq_index_mode question_index_mode: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode' + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode' + description: QuestionIndexMode is combined or separate. + enum: + - combined + - separate + x-agent: faq_question_index_mode type: object github_com_Tencent_WeKnora_internal_types.FAQEntry: properties: @@ -3346,6 +3406,7 @@ definitions: override it per document through KnowledgeProcessOverrides.ImageAttrsEnabled. type: boolean + x-agent: true image_vector_enabled: description: |- ImageVectorEnabled lets a knowledge base whose embedding model takes @@ -3355,9 +3416,12 @@ definitions: and widens vector recall. Existing knowledge bases stay off after an upgrade because the stored JSON has no such key. type: boolean + x-agent: true model_id: - description: Model ID + description: Model ID used when describing images. Empty uses the knowledge + base's caption model. type: string + x-agent: image_model_id type: object github_com_Tencent_WeKnora_internal_types.IndexConfig: properties: @@ -3763,19 +3827,26 @@ definitions: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig' description: ASR config (Automatic Speech Recognition) + x-agent: true + x-agent-detail: true auto_tag_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig' description: AutoTagConfig controls asynchronous association of existing tags after parsing. + x-agent: true + x-agent-detail: true chunk_count: description: Chunk count (not stored in database, calculated on query) type: integer x-agent: true + x-agent-response: true chunking_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' description: Chunking configuration + x-agent: true + x-agent-detail: true created_at: description: Creation time of the knowledge base type: string @@ -3802,17 +3873,23 @@ definitions: type: string x-agent: true embedding_model_id: - description: ID of the embedding model + description: ID of the embedding model. model.list returns the ids. Cannot + change after the knowledge base has documents. type: string + x-agent: embedding_model_id extract_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig' description: Extract config + x-agent: true + x-agent-detail: true faq_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' description: FAQConfig stores FAQ specific configuration such as indexing strategy + x-agent: true + x-agent-detail: true generated_profile: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfile' @@ -3824,10 +3901,13 @@ definitions: description: Unique identifier of the knowledge base type: string x-agent: knowledge_base_id + x-agent-response: true image_processing_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig' description: Image processing configuration + x-agent: true + x-agent-detail: true indexing_strategy: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy' @@ -3835,6 +3915,7 @@ definitions: IndexingStrategy controls which indexing pipelines are active for this knowledge base. Pipelines: vector search, keyword search, wiki generation, knowledge graph extraction. x-agent: true + x-agent-response: true is_pinned: description: |- IsPinned and PinnedAt are computed per-caller from user_kb_pins @@ -3851,6 +3932,7 @@ definitions: FAQ type knowledge bases) type: boolean x-agent: true + x-agent-response: true is_temporary: description: Whether this knowledge base is temporary (ephemeral) and should be hidden from UI @@ -3859,10 +3941,12 @@ definitions: description: Knowledge count (not stored in database, calculated on query) type: integer x-agent: true + x-agent-response: true name: description: Name of the knowledge base type: string x-agent: true + x-agent-required: true pinned_at: description: |- PinnedAt records when the current caller pinned this knowledge @@ -3873,17 +3957,22 @@ definitions: processed (for document type knowledge bases) type: integer x-agent: true + x-agent-response: true profile_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig' description: |- ProfileConfig controls automatic generation of the knowledge-base description from per-document profiles (document knowledge bases only). + x-agent: true + x-agent-detail: true question_generation_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig' description: QuestionGenerationConfig stores question generation configuration for document knowledge bases + x-agent: true + x-agent-detail: true share_count: description: ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database) @@ -3893,6 +3982,7 @@ definitions: StorageBackendID binds this KB to one concrete storage instance. The legacy provider field remains readable during migration only. type: string + x-agent: storage_backend_id storage_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.StorageConfig' @@ -3904,19 +3994,27 @@ definitions: description: 'Storage provider config (new): only stores provider selection; credentials from workspace StorageEngineConfig' summary_model_id: - description: Summary model ID + description: Summary model ID. model.list returns the ids. Used for summaries, + and as the default for auto-tagging and the AI description. type: string + x-agent: summary_model_id tenant_id: description: Workspace ID type: integer type: - description: Type of the knowledge base (document, faq, etc.) + description: 'Type of the knowledge base: document, faq or wiki. Empty means + document.' + enum: + - document + - faq + - wiki type: string x-agent: true updated_at: description: Last updated time of the knowledge base type: string x-agent: true + x-agent-response: true vector_store_id: description: |- VectorStoreID references the VectorStore this knowledge base is bound to. @@ -3926,18 +4024,30 @@ definitions: enforcement lives at the GORM layer (`<-:create`) plus the service-layer KB update path, which omits this field from its update DTO. type: string + x-agent: vector_store_id vlm_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig' description: VLM config + x-agent: true + x-agent-detail: true wiki_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig' description: WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases) + x-agent: true + x-agent-detail: true + required: + - name type: object github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig: properties: + asr_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig' + description: ASRConfig replaces speech-recognition settings when set. nil + means no change. auto_tag_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig' @@ -3947,6 +4057,16 @@ definitions: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' description: Chunking configuration + embedding_model_id: + description: |- + EmbeddingModelID changes the embedding model. nil means no change. + A knowledge base that already has documents cannot switch models. + type: string + extract_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig' + description: ExtractConfig replaces graph extraction settings when set. nil + means no change. faq_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' @@ -3975,6 +4095,17 @@ definitions: description: |- ProfileConfig controls optional automatic knowledge-base description generation. nil means "no change" when updating. + question_generation_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig' + description: QuestionGenerationConfig replaces generated-question settings + when set. nil means no change. + storage_backend_id: + description: StorageBackendID rebinds file storage. nil means no change. + type: string + summary_model_id: + description: SummaryModelID changes the summary model. nil means no change. + type: string wiki_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig' @@ -4026,16 +4157,20 @@ definitions: github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig: properties: custom_instructions: - description: |- - CustomInstructions is appended to the stable system prompt, e.g. the - audience the description should address or terms to keep. + description: CustomInstructions is extra guidance for the description, such + as the audience. The format stays fixed. type: string + x-agent: profile_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" enabled: + description: Enabled turns the AI knowledge-base description on. type: boolean + x-agent: profile_enabled model_id: - description: ModelID overrides the chat model; empty falls back to the KB - summary model. + description: ModelID overrides the summary model. Empty uses summary_model_id. type: string + x-agent: profile_model_id type: object github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileStats: properties: @@ -4687,6 +4822,7 @@ definitions: type: string x-agent: true x-agent-max-bytes: "800000" + x-agent-required: true process_config: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeProcessOverrides' status: @@ -4696,6 +4832,7 @@ definitions: - publish type: string x-agent: true + x-agent-required: true tag_ids: items: type: string @@ -6074,16 +6211,24 @@ definitions: github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig: properties: custom_instructions: - description: |- - CustomInstructions describes the intended audience or question style. - It is appended to the stable system question-generation template. + description: CustomInstructions describes who the questions are for. The question + format stays fixed. type: string + x-agent: question_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" enabled: + description: Enabled turns question generation on. Generated questions are + indexed beside the chunk. type: boolean + x-agent: question_generation_enabled question_count: - description: 'Number of questions to generate per chunk (default: 3, max: - 10)' + description: QuestionCount is how many questions to write per chunk, from + 1 to 10. + maximum: 10 + minimum: 1 type: integer + x-agent: question_count type: object github_com_Tencent_WeKnora_internal_types.QuestionOrigin: properties: @@ -8002,22 +8147,28 @@ definitions: description: Base URL type: string custom_instructions: - description: |- - CustomInstructions adds KB-specific image interpretation guidance without - replacing the system-owned OCR and Markdown output contract. + description: CustomInstructions adds image-reading guidance. The OCR and Markdown + format stay fixed. type: string + x-agent: vlm_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" description_language: - description: |- - DescriptionLanguage controls the language used for generated image - captions. Empty means follow the document/request language. + description: DescriptionLanguage is the language of generated image captions. + Empty follows the document language. type: string + x-agent: vlm_language enabled: + description: Enabled turns image captions on. Also send vlm_model_id. type: boolean + x-agent: vlm_enabled interface_type: description: 'Interface Type: "ollama" or "openai"' type: string model_id: + description: Model that writes image captions. model.list returns the ids. type: string + x-agent: vlm_model_id model_name: description: |- 兼容老版本 @@ -8373,21 +8524,29 @@ definitions: github_com_Tencent_WeKnora_internal_types.WikiConfig: properties: content_instructions: - description: |- - ContentInstructions controls tone, structure and emphasis for generated - summary/entity/index prose. Citation and merge rules remain system-owned. + description: ContentInstructions sets tone and emphasis for generated Wiki + prose. Citations stay fixed. type: string + x-agent: wiki_content_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" extraction_granularity: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiExtractionGranularity' - description: |- - ExtractionGranularity controls how many candidate slugs Pass 0 extracts - per document. Empty / unknown value is treated as WikiExtractionStandard. + description: ExtractionGranularity is focused, standard or exhaustive. Empty + means standard. + enum: + - focused + - standard + - exhaustive + x-agent: wiki_granularity extraction_instructions: - description: |- - ExtractionInstructions tells candidate extraction which domain concepts - to emphasize without replacing the stable JSON/citation protocol. + description: ExtractionInstructions tells page extraction which concepts to + keep. The output format stays fixed. type: string + x-agent: wiki_extraction_instructions + x-agent-detail: true + x-agent-max-bytes: "4000" ingest_batch_size: description: |- IngestBatchSize controls how many pending ops a single batch claims and @@ -8422,13 +8581,17 @@ definitions: DB connection pool size. Same multiplier caveat as IngestMapParallel. type: integer max_pages_per_ingest: - description: MaxPagesPerIngest limits pages created/updated per ingest operation - (0 = no limit) + description: MaxPagesPerIngest limits pages created or updated per ingest. + 0 means no limit. + maximum: 1000 + minimum: 0 type: integer + x-agent: wiki_max_pages synthesis_model_id: - description: SynthesisModelID is the LLM model ID used for wiki page generation - and updates + description: SynthesisModelID is the model that writes Wiki pages. Empty uses + summary_model_id. type: string + x-agent: wiki_synthesis_model_id type: object github_com_Tencent_WeKnora_internal_types.WikiExtractionGranularity: enum: @@ -9337,6 +9500,19 @@ definitions: user: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UserInfo' type: object + internal_handler.CreateTagRequest: + properties: + color: + type: string + name: + description: Tag name, unique in this knowledge base + type: string + x-agent: true + sort_order: + type: integer + required: + - name + type: object internal_handler.CurrentUserCapabilities: properties: auto_accept_invitation: @@ -9851,21 +10027,28 @@ definitions: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig' description: ASR config (Automatic Speech Recognition) + x-agent: true + x-agent-detail: true auto_tag_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig' description: AutoTagConfig controls asynchronous association of existing tags after parsing. + x-agent: true + x-agent-detail: true capabilities: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KBCapabilities' chunk_count: description: Chunk count (not stored in database, calculated on query) type: integer x-agent: true + x-agent-response: true chunking_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' description: Chunking configuration + x-agent: true + x-agent-detail: true created_at: description: Creation time of the knowledge base type: string @@ -9892,17 +10075,23 @@ definitions: type: string x-agent: true embedding_model_id: - description: ID of the embedding model + description: ID of the embedding model. model.list returns the ids. Cannot + change after the knowledge base has documents. type: string + x-agent: embedding_model_id extract_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig' description: Extract config + x-agent: true + x-agent-detail: true faq_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' description: FAQConfig stores FAQ specific configuration such as indexing strategy + x-agent: true + x-agent-detail: true generated_profile: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfile' @@ -9914,10 +10103,13 @@ definitions: description: Unique identifier of the knowledge base type: string x-agent: knowledge_base_id + x-agent-response: true image_processing_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig' description: Image processing configuration + x-agent: true + x-agent-detail: true indexing_strategy: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy' @@ -9925,6 +10117,7 @@ definitions: IndexingStrategy controls which indexing pipelines are active for this knowledge base. Pipelines: vector search, keyword search, wiki generation, knowledge graph extraction. x-agent: true + x-agent-response: true is_pinned: description: |- IsPinned and PinnedAt are computed per-caller from user_kb_pins @@ -9941,6 +10134,7 @@ definitions: FAQ type knowledge bases) type: boolean x-agent: true + x-agent-response: true is_temporary: description: Whether this knowledge base is temporary (ephemeral) and should be hidden from UI @@ -9949,6 +10143,7 @@ definitions: description: Knowledge count (not stored in database, calculated on query) type: integer x-agent: true + x-agent-response: true my_permission: description: |- MyPermission is the caller's role on a knowledge base shared from @@ -9963,6 +10158,7 @@ definitions: description: Name of the knowledge base type: string x-agent: true + x-agent-required: true pinned_at: description: |- PinnedAt records when the current caller pinned this knowledge @@ -9973,17 +10169,22 @@ definitions: processed (for document type knowledge bases) type: integer x-agent: true + x-agent-response: true profile_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig' description: |- ProfileConfig controls automatic generation of the knowledge-base description from per-document profiles (document knowledge bases only). + x-agent: true + x-agent-detail: true question_generation_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig' description: QuestionGenerationConfig stores question generation configuration for document knowledge bases + x-agent: true + x-agent-detail: true share_count: description: ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database) @@ -9993,6 +10194,7 @@ definitions: StorageBackendID binds this KB to one concrete storage instance. The legacy provider field remains readable during migration only. type: string + x-agent: storage_backend_id storage_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.StorageConfig' @@ -10004,19 +10206,27 @@ definitions: description: 'Storage provider config (new): only stores provider selection; credentials from workspace StorageEngineConfig' summary_model_id: - description: Summary model ID + description: Summary model ID. model.list returns the ids. Used for summaries, + and as the default for auto-tagging and the AI description. type: string + x-agent: summary_model_id tenant_id: description: Workspace ID type: integer type: - description: Type of the knowledge base (document, faq, etc.) + description: 'Type of the knowledge base: document, faq or wiki. Empty means + document.' + enum: + - document + - faq + - wiki type: string x-agent: true updated_at: description: Last updated time of the knowledge base type: string x-agent: true + x-agent-response: true vector_store_engine_type: type: string vector_store_id: @@ -10028,6 +10238,7 @@ definitions: enforcement lives at the GORM layer (`<-:create`) plus the service-layer KB update path, which omits this field from its update DTO. type: string + x-agent: vector_store_id vector_store_name: type: string vector_store_source: @@ -10038,11 +10249,17 @@ definitions: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig' description: VLM config + x-agent: true + x-agent-detail: true wiki_config: allOf: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig' description: WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases) + x-agent: true + x-agent-detail: true + required: + - name type: object internal_handler.KnowledgeSearchKnowledgeResponse: properties: @@ -10116,6 +10333,38 @@ definitions: trace: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SpanTreeNode' type: object + internal_handler.KnowledgeTagBatchRequest: + properties: + kb_id: + description: Knowledge base the documents belong to. + type: string + x-agent: knowledge_base_id + x-agent-required: true + knowledge_ids: + description: Documents that receive the same tags. Mutually exclusive with + updates. + items: + type: string + type: array + x-agent: true + x-agent-maximum: "20" + x-agent-required: true + tag_ids: + description: Tags to set on every listed document. An empty list clears them. + items: + type: string + type: array + x-agent: true + x-agent-maximum: "50" + x-agent-required: true + updates: + additionalProperties: + items: + type: string + type: array + description: Map of knowledge id to the tag ids that replace its current tags. + type: object + type: object internal_handler.ListAgentsResponse: properties: data: @@ -10596,6 +10845,73 @@ definitions: type: boolean x-agent: true type: object + internal_handler.PatchKnowledgeBaseRequest: + properties: + asr_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ASRConfig' + description: Speech transcription. + auto_tag_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AutoTagConfig' + description: Automatic tagging. + chunking_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' + description: Chunking settings. Only the fields present are changed. + description: + description: New description. Omit to keep it; an empty string clears it. + type: string + x-agent: true + embedding_model_id: + description: Embedding model. Cannot change after the knowledge base has documents. + type: string + x-agent: embedding_model_id + extract_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig' + description: Graph extraction. Node types stay in the knowledge base editor. + faq_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' + description: FAQ indexing. Only for an FAQ knowledge base. + image_processing_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig' + description: Image description settings. + indexing_strategy: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.IndexingStrategy' + description: Indexing pipelines. A flag left out stays as it is. + name: + description: New name. Omit to keep the current one. + type: string + x-agent: true + profile_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseProfileConfig' + description: AI description of the knowledge base. + question_generation_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig' + description: Generated questions for each chunk. + storage_backend_id: + description: Storage instance to bind. Omit to keep the current one. + type: string + x-agent: storage_backend_id + summary_model_id: + description: Summary model. model.list returns the ids. + type: string + x-agent: summary_model_id + vlm_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig' + description: Image captions. + wiki_config: + allOf: + - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiConfig' + description: Wiki page settings. + type: object internal_handler.PlaceholderGroups: properties: agent_system_prompt: @@ -11389,6 +11705,17 @@ definitions: etc. by the JSON unmarshaller). Service.encodeForType normalises these against the registry's declared type and rejects mismatches. type: object + internal_handler.UpdateTagRequest: + properties: + color: + type: string + name: + description: New name. Omit to keep the current one. + type: string + x-agent: true + sort_order: + type: integer + type: object internal_handler.ValidateTokenResponse: properties: message: @@ -14991,6 +15318,14 @@ paths: summary: 创建知识库 tags: - 知识库 + x-agent: + id: knowledge_base.create + label_param: name + risk: write + 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. /knowledge-bases/{id}: delete: consumes: @@ -15002,6 +15337,7 @@ paths: name: id required: true type: string + x-agent: knowledge_base_id produces: - application/json responses: @@ -15027,6 +15363,13 @@ paths: summary: 删除知识库 tags: - 知识库 + x-agent: + id: knowledge_base.delete + label: name + risk: destructive + target: knowledge_base.get + x-agent-hint: Deletes the knowledge base and every document in it. Cannot be + undone. Only the owner can delete it. get: consumes: - application/json @@ -15077,6 +15420,62 @@ paths: risk: read x-agent-hint: Check which indexes are enabled (vector, keyword, Wiki, graph) and whether documents are processing. + patch: + consumes: + - application/json + description: 修改请求里出现的设置。未出现的字段保持不变,包括分块、索引和模型里没写到的项。 + parameters: + - description: 知识库ID + in: path + name: id + required: true + type: string + x-agent: knowledge_base_id + - description: 要修改的字段 + in: body + name: request + required: true + schema: + $ref: '#/definitions/internal_handler.PatchKnowledgeBaseRequest' + produces: + - application/json + responses: + "200": + description: 更新后的知识库 + schema: + allOf: + - $ref: '#/definitions/internal_handler.DataResponse' + - properties: + data: + $ref: '#/definitions/internal_handler.KnowledgeBaseView' + type: object + "400": + description: 请求参数错误 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + "403": + description: 无权限 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + "404": + description: 知识库不存在 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: 部分更新知识库 + tags: + - 知识库 + x-agent: + id: knowledge_base.update + label: name + risk: write + target: knowledge_base.get + 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. put: consumes: - application/json @@ -16426,8 +16825,8 @@ paths: label: name risk: write target: knowledge_base.get - 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. /knowledge-bases/{id}/knowledge/url: post: consumes: @@ -16814,19 +17213,13 @@ paths: name: id required: true type: string + x-agent: knowledge_base_id - description: 标签信息 in: body name: request required: true schema: - properties: - color: - type: string - name: - type: string - sort_order: - type: integer - type: object + $ref: '#/definitions/internal_handler.CreateTagRequest' produces: - application/json responses: @@ -16849,6 +17242,13 @@ paths: summary: 创建标签 tags: - 标签管理 + x-agent: + id: knowledge_base.create_tag + label: name + risk: write + target: knowledge_base.get + x-agent-hint: Creates a tag in the knowledge base. Pass the returned tag id + to knowledge.set_tags. /knowledge-bases/{id}/tags/{tag_id}: delete: consumes: @@ -16860,11 +17260,13 @@ paths: name: id required: true type: string + x-agent: knowledge_base_id - description: 标签ID (UUID或seq_id) in: path name: tag_id required: true type: string + x-agent: tag_id - description: 强制删除 in: query name: force @@ -16895,6 +17297,14 @@ paths: summary: 删除标签 tags: - 标签管理 + x-agent: + id: knowledge_base.delete_tag + label: name + risk: destructive + target: knowledge_base.get + 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. put: consumes: - application/json @@ -16905,17 +17315,19 @@ paths: name: id required: true type: string + x-agent: knowledge_base_id - description: 标签ID (UUID或seq_id) in: path name: tag_id required: true type: string + x-agent: tag_id - description: 标签更新信息 in: body name: request required: true schema: - type: object + $ref: '#/definitions/internal_handler.UpdateTagRequest' produces: - application/json responses: @@ -16938,6 +17350,13 @@ paths: summary: 更新标签 tags: - 标签管理 + x-agent: + id: knowledge_base.update_tag + label: name + risk: write + target: knowledge_base.get + x-agent-hint: Renames a tag. tag_id comes from knowledge_base.list_tags. A field + left out is kept. /knowledge-bases/copy: post: consumes: @@ -17675,6 +18094,7 @@ paths: name: id required: true type: string + x-agent: knowledge_id - description: 手工知识内容 in: body name: request @@ -17703,6 +18123,14 @@ paths: summary: 更新手工知识 tags: - 知识管理 + x-agent: + id: knowledge.update_manual + label: title + risk: write + target: knowledge.get + 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. /knowledge/move: post: consumes: @@ -17841,14 +18269,14 @@ paths: put: consumes: - application/json - description: 批量更新知识条目的标签。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析 + description: 批量更新知识条目的标签。传 updates,或传 knowledge_ids 与 tag_ids。可选 kb_id:指定时按该知识库校验编辑权限并用于共享知识库的空间解析 parameters: - - description: 标签更新请求(updates 必填,kb_id 可选) + - description: 标签更新请求 in: body name: request required: true schema: - type: object + $ref: '#/definitions/internal_handler.KnowledgeTagBatchRequest' produces: - application/json responses: @@ -17866,6 +18294,19 @@ paths: summary: 批量更新知识标签 tags: - 知识管理 + x-agent: + id: knowledge.set_tags + items: + as: knowledge_id + label: title + param: knowledge_ids + target: knowledge.get + label: name + risk: write + target: knowledge_base.get + 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. /knowledgebase/{kb_id}/wiki/auto-fix: post: description: Automatically fix fixable wiki issues (broken links, etc.) diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 144a50c4..2727fd00 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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}', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 39c5d000..48fe073a 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -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}', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 25278309..8ff116a0 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: { diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index c7b416f6..9608ff93 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: { diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 547e846f..384d5220 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: { diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 150fc273..d8c5875b 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -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: { diff --git a/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs b/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs index 0fd1d6bc..16e5faca 100644 --- a/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs +++ b/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs @@ -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 \{/) +}) diff --git a/frontend/src/views/chat/components/ToolApprovalCard.vue b/frontend/src/views/chat/components/ToolApprovalCard.vue index 3e433f74..92ad3182 100644 --- a/frontend/src/views/chat/components/ToolApprovalCard.vue +++ b/frontend/src/views/chat/components/ToolApprovalCard.vue @@ -2,6 +2,12 @@
{{ $t('agentStream.toolApproval.dockQuestion', { target: targetLabel }) }}
{{ descriptionParts.head }}
+
+
+
{{ approvalFieldLabel(field.label) }}
+
{{ approvalFieldValue(field.label, field.value) }}
+
+
@@ -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 = { + 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 = { + 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(() => { diff --git a/frontend/src/views/chat/components/agent-interaction-card.less b/frontend/src/views/chat/components/agent-interaction-card.less index 3a8ea7f8..159b458b 100644 --- a/frontend/src/views/chat/components/agent-interaction-card.less +++ b/frontend/src/views/chat/components/agent-interaction-card.less @@ -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; diff --git a/internal/agent/operations/catalog_test.go b/internal/agent/operations/catalog_test.go index ffa6d642..cd243691 100644 --- a/internal/agent/operations/catalog_test.go +++ b/internal/agent/operations/catalog_test.go @@ -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) +} diff --git a/internal/agent/operations/request.go b/internal/agent/operations/request.go index 5e24d177..31ca80c8 100644 --- a/internal/agent/operations/request.go +++ b/internal/agent/operations/request.go @@ -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)) diff --git a/internal/agent/operations/spec.go b/internal/agent/operations/spec.go index c4b3aa57..ea894843 100644 --- a/internal/agent/operations/spec.go +++ b/internal/agent/operations/spec.go @@ -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) } diff --git a/internal/agent/operations/spec_test.go b/internal/agent/operations/spec_test.go index 5b28022f..ed12e649 100644 --- a/internal/agent/operations/spec_test.go +++ b/internal/agent/operations/spec_test.go @@ -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) diff --git a/internal/agent/tools/operations.go b/internal/agent/tools/operations.go index fee140f2..62cbdb99 100644 --- a/internal/agent/tools/operations.go +++ b/internal/agent/tools/operations.go @@ -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 != "" { diff --git a/internal/agent/tools/operations_test.go b/internal/agent/tools/operations_test.go index dba6959d..5bd89332 100644 --- a/internal/agent/tools/operations_test.go +++ b/internal/agent/tools/operations_test.go @@ -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))}, diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index 4af4739f..6d29b00e 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -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 diff --git a/internal/application/service/knowledgebase_storage_update_test.go b/internal/application/service/knowledgebase_storage_update_test.go new file mode 100644 index 00000000..be164721 --- /dev/null +++ b/internal/application/service/knowledgebase_storage_update_test.go @@ -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) + }) + } +} diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index b3de7271..e7f29659 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -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 != "" { diff --git a/internal/handler/knowledge_tag_batch_test.go b/internal/handler/knowledge_tag_batch_test.go new file mode 100644 index 00000000..59c5eb74 --- /dev/null +++ b/internal/handler/knowledge_tag_batch_test.go @@ -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)) + } +} diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 9d5eb0a3..bf35c549 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -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() diff --git a/internal/handler/knowledgebase_patch_test.go b/internal/handler/knowledgebase_patch_test.go new file mode 100644 index 00000000..f82463a2 --- /dev/null +++ b/internal/handler/knowledgebase_patch_test.go @@ -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) +} diff --git a/internal/handler/knowledgebase_settings_access_test.go b/internal/handler/knowledgebase_settings_access_test.go new file mode 100644 index 00000000..bc232382 --- /dev/null +++ b/internal/handler/knowledgebase_settings_access_test.go @@ -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) + }) + } + } + } +} diff --git a/internal/handler/tag.go b/internal/handler/tag.go index 9935f09c..c4154860 100644 --- a/internal/handler/tag.go +++ b/internal/handler/tag.go @@ -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() diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go index 089e7857..25d71238 100644 --- a/internal/router/router_api_key_capabilities_test.go +++ b/internal/router/router_api_key_capabilities_test.go @@ -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"}, diff --git a/internal/router/routes_knowledge.go b/internal/router/routes_knowledge.go index 87942312..77de585f 100644 --- a/internal/router/routes_knowledge.go +++ b/internal/router/routes_knowledge.go @@ -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) diff --git a/internal/types/knowledge.go b/internal/types/knowledge.go index 891bbf42..efee0096 100644 --- a/internal/types/knowledge.go +++ b/internal/types/knowledge.go @@ -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"` diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go index 4e9e6b4a..9e66fb68 100644 --- a/internal/types/knowledgebase.go +++ b/internal/types/knowledgebase.go @@ -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 diff --git a/internal/types/knowledgebase_profile.go b/internal/types/knowledgebase_profile.go index d1028818..222c6607 100644 --- a/internal/types/knowledgebase_profile.go +++ b/internal/types/knowledgebase_profile.go @@ -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. diff --git a/internal/types/wiki_page.go b/internal/types/wiki_page.go index 2e7c905f..61f658ac 100644 --- a/internal/types/wiki_page.go +++ b/internal/types/wiki_page.go @@ -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 diff --git a/website-docs/04-api/02-api-chunks.md b/website-docs/04-api/02-api-chunks.md index 7b5d9bfd..e20b0b21 100644 --- a/website-docs/04-api/02-api-chunks.md +++ b/website-docs/04-api/02-api-chunks.md @@ -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" ``` ## 分块调试 diff --git a/website-docs/04-api/02-api-knowledge.md b/website-docs/04-api/02-api-knowledge.md index 1345ee26..a0fcad45 100644 --- a/website-docs/04-api/02-api-knowledge.md +++ b/website-docs/04-api/02-api-knowledge.md @@ -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}`