From 0785a498e961e38a5e9d35ec2a55a7ee00f5822f Mon Sep 17 00:00:00 2001 From: sn1p4am Date: Thu, 16 Apr 2026 14:09:36 +0800 Subject: [PATCH 001/192] fix: use explicit localhost for docreader health probes --- docker-compose.dev.yml | 2 +- docker-compose.yml | 2 +- docreader/README.md | 2 +- helm/templates/docreader.yaml | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 84cb6712..de4bbeac 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -150,7 +150,7 @@ services: - MINERU_ENDPOINT=${MINERU_ENDPOINT:-} - MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-} healthcheck: - test: ["CMD", "grpc_health_probe", "-addr=:50051"] + test: ["CMD", "grpc_health_probe", "-addr=localhost:50051"] interval: 30s timeout: 10s retries: 3 diff --git a/docker-compose.yml b/docker-compose.yml index 54549cbe..b7fc5bb7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -171,7 +171,7 @@ services: - DOCREADER_IMAGE_OUTPUT_DIR=/tmp/docreader - MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-} healthcheck: - test: ["CMD", "grpc_health_probe", "-addr=:50051"] + test: ["CMD", "grpc_health_probe", "-addr=localhost:50051"] interval: 30s timeout: 10s retries: 3 diff --git a/docreader/README.md b/docreader/README.md index 19f49541..680cd6dc 100644 --- a/docreader/README.md +++ b/docreader/README.md @@ -229,7 +229,7 @@ DocReader 服务配置了健康检查: ```yaml healthcheck: - test: ["CMD", "grpc_health_probe", "-addr=:50051"] + test: ["CMD", "grpc_health_probe", "-addr=localhost:50051"] interval: 30s timeout: 10s retries: 3 diff --git a/helm/templates/docreader.yaml b/helm/templates/docreader.yaml index c95ebe7b..229f8bc2 100644 --- a/helm/templates/docreader.yaml +++ b/helm/templates/docreader.yaml @@ -55,7 +55,7 @@ spec: exec: command: - grpc_health_probe - - -addr=:50051 + - -addr=localhost:50051 initialDelaySeconds: 30 periodSeconds: 10 timeoutSeconds: 5 @@ -64,7 +64,7 @@ spec: exec: command: - grpc_health_probe - - -addr=:50051 + - -addr=localhost:50051 initialDelaySeconds: 10 periodSeconds: 5 timeoutSeconds: 3 From a78182cfc75726d5d5c0fcfa472b50f708337d81 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 15 Apr 2026 16:24:37 +0800 Subject: [PATCH 002/192] feat(handler): validate bucket name format and improve MinIO error handling - Added validation for bucket name format to ensure it meets specified criteria, returning an error message for invalid formats. - Simplified error messages for MinIO client creation and bucket auto-creation failures, enhancing clarity for users. - Updated success messages to reflect the correct status of bucket creation without public-read policy settings. This update improves the robustness of the MinIO integration and enhances user feedback during storage checks. --- internal/handler/system.go | 38 ++++++++++---------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/internal/handler/system.go b/internal/handler/system.go index f067f407..1af6391d 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -824,6 +824,11 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ return } + if cfg.BucketName != "" && !cosFieldPattern.MatchString(cfg.BucketName) { + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}}) + return + } + endpoint, accessKeyID, secretAccessKey := cfg.Endpoint, cfg.AccessKeyID, cfg.SecretAccessKey if cfg.Mode != "remote" { endpoint = os.Getenv("MINIO_ENDPOINT") @@ -846,7 +851,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ err := file.CheckMinioConnectivity(ctx, endpoint, accessKeyID, secretAccessKey, cfg.BucketName, cfg.UseSSL) if err != nil { errMsg := err.Error() - // If bucket does not exist, auto-create it with public-read policy + // If bucket does not exist, auto-create it if strings.Contains(errMsg, "does not exist") && cfg.BucketName != "" { logger.Info(ctx, "Storage check: bucket does not exist, attempting auto-creation", "bucket", cfg.BucketName) minioClient, clientErr := minio.New(endpoint, &minio.Options{ @@ -854,39 +859,16 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ Secure: cfg.UseSSL, }) if clientErr != nil { - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("创建 MinIO 客户端失败: %s", sanitizeStorageCheckError(clientErr))}}) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to create MinIO client: %s", sanitizeStorageCheckError(clientErr))}}) return } if mkErr := minioClient.MakeBucket(ctx, cfg.BucketName, minio.MakeBucketOptions{}); mkErr != nil { logger.Error(ctx, "Storage check: failed to create bucket", "bucket", cfg.BucketName, "error", mkErr) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("自动创建 Bucket「%s」失败: %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}}) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to auto-create Bucket '%s': %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}}) return } - // Set public-read policy - publicReadPolicy := fmt.Sprintf(`{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": {"AWS": ["*"]}, - "Action": ["s3:GetBucketLocation", "s3:ListBucket"], - "Resource": ["arn:aws:s3:::%s"] - }, - { - "Effect": "Allow", - "Principal": {"AWS": ["*"]}, - "Action": ["s3:GetObject"], - "Resource": ["arn:aws:s3:::%s/*"] - } - ] - }`, cfg.BucketName, cfg.BucketName) - if policyErr := minioClient.SetBucketPolicy(ctx, cfg.BucketName, publicReadPolicy); policyErr != nil { - logger.Error(ctx, "Storage check: bucket created but failed to set public-read policy", "bucket", cfg.BucketName, "error", policyErr) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」已自动创建,但设置公有读策略失败,请手动配置权限", cfg.BucketName)}}) - return - } - logger.Info(ctx, "Storage check: bucket created with public-read policy", "bucket", cfg.BucketName) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」不存在,已自动创建并设置公有读权限", cfg.BucketName)}}) + logger.Info(ctx, "Storage check: bucket created", "bucket", cfg.BucketName) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket '%s' does not exist, and has been automatically created", cfg.BucketName)}}) return } logger.Error(ctx, "Storage check: MinIO connectivity failed", "error", err) From 7c40fb6ac9bdf0139964ee7f7fe0d13a11560fb6 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 12:24:57 +0800 Subject: [PATCH 003/192] feat: enhance URL validation and timeout handling in knowledge base components - Added isValidURL function to validate URLs before rendering links in the document content component, preventing invalid links from being clickable. - Refactored timeout handling in KnowledgeBase.vue to use setTimeout instead of setInterval, improving performance and resource management. - Ensured that timeouts are cleared appropriately to avoid memory leaks and unnecessary polling. This update improves the robustness of URL handling and optimizes the component's performance. --- frontend/src/components/doc-content.vue | 4 +- .../src/views/knowledge/KnowledgeBase.vue | 52 ++++++++++++++++--- internal/utils/security.go | 4 +- 3 files changed, 49 insertions(+), 11 deletions(-) diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 6f659607..f22c41d8 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -8,7 +8,7 @@ import mermaid from "mermaid"; import { onMounted, ref, nextTick, onUnmounted, watch, computed } from "vue"; import { downKnowledgeDetails, deleteGeneratedQuestion, getChunkByIdOnly, previewKnowledgeFile } from "@/api/knowledge-base/index"; import { MessagePlugin, DialogPlugin } from "tdesign-vue-next"; -import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security'; +import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages, isValidURL } from '@/utils/security'; import { openMermaidFullscreen } from '@/utils/mermaidViewer'; import { useI18n } from 'vue-i18n'; import DocumentPreview from '@/components/document-preview.vue'; @@ -778,7 +778,7 @@ const handleDetailsScroll = () => {
{{ $t('knowledgeBase.urlSource') }} `; }); - excelHtml.value = html; + excelHtml.value = sanitizeHTML(html); } async function renderText(blob: Blob, fileType: string) { @@ -223,7 +224,9 @@ async function renderMarkdown(blob: Blob) { return `
${highlighted}
`; }; marked.use({ renderer }); - markdownHtml.value = marked.parse(text); + const safeText = safeMarkdownToHTML(text); + const rawHtml = marked.parse(safeText); + markdownHtml.value = sanitizeHTML(rawHtml); } function onImageLoad(e: Event) { diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 059eea8a..993ecf40 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -189,10 +189,6 @@ const renderToken = (token) => { } }; -const myMarkdown = (res) => { - return marked.parse(res, { renderer }) -} - // 获取实际内容 const getActualContent = () => { return (props.content || props.session?.content || '').trim(); From 1938094dccad9c6ecbdaa4218a4bf5a46024d37e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 15:15:33 +0800 Subject: [PATCH 006/192] feat(parser): add PDFScannedParser for handling scanned PDFs - Introduced PDFScannedParser as a fallback parser for scanned PDFs that converts pages into images for OCR processing. - Updated PDFParser to include PDFScannedParser in the parsing chain, enhancing the document parsing capabilities for scanned content. - Improved logging for better error tracking during PDF parsing operations. --- docreader/parser/pdf_parser.py | 57 ++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/docreader/parser/pdf_parser.py b/docreader/parser/pdf_parser.py index f98ab3eb..c5917e18 100644 --- a/docreader/parser/pdf_parser.py +++ b/docreader/parser/pdf_parser.py @@ -1,15 +1,68 @@ +from docreader.models.document import Document +from docreader.parser.base_parser import BaseParser from docreader.parser.chain_parser import FirstParser from docreader.parser.markitdown_parser import MarkitdownParser +import io +import os +import base64 +import logging + +logger = logging.getLogger(__name__) + +class PDFScannedParser(BaseParser): + """Fallback parser for scanned PDFs. + + If the primary parser extracts no text (e.g. Markitdown on a scanned PDF), + this parser converts each page into an image. The Go App will then perform + OCR on the extracted images. + """ + + def parse_into_text(self, content: bytes) -> Document: + import pdfplumber + images = {} + markdown_lines = [] + + base_name = os.path.splitext(self.file_name or "document")[0] + + logger.info("PDFScannedParser: Attempting to convert PDF pages to images for %s", self.file_name) + + try: + with pdfplumber.open(io.BytesIO(content)) as pdf: + for i, page in enumerate(pdf.pages): + img_obj = page.to_image(resolution=150).original + img_byte_arr = io.BytesIO() + img_obj.save(img_byte_arr, format="PNG") + img_bytes = img_byte_arr.getvalue() + + page_filename = f"{base_name}_page_{i+1}.png" + ref_path = f"images/{page_filename}" + + markdown_lines.append(f"![{page_filename}]({ref_path})") + images[ref_path] = base64.b64encode(img_bytes).decode("utf-8") + + text = "\n\n".join(markdown_lines) + return Document( + content=text, + images=images, + metadata={ + "image_source_type": "scanned_pdf", + "page_count": len(pdf.pages) + } + ) + except Exception as e: + logger.exception("PDFScannedParser failed to parse PDF: %v", e) + raise e class PDFParser(FirstParser): """PDF Parser using chain of responsibility pattern Attempts to parse PDF files using multiple parser backends in order: - 1. MinerUParser - Primary parser for PDF documents + 1. MinerUParser - Primary parser for PDF documents (if enabled) 2. MarkitdownParser - Fallback parser if MinerU fails + 3. PDFScannedParser - Final fallback for scanned PDFs The first successful parser result will be returned. """ # Parser classes to try in order (chain of responsibility pattern) - _parser_cls = (MarkitdownParser,) + _parser_cls = (MarkitdownParser, PDFScannedParser) From af58e9cff4446f21e8a57908aa01b2b4f30e922e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 15:15:46 +0800 Subject: [PATCH 007/192] fix(repository): ensure expandedTopK is at least params.TopK in VectorRetrieve - Added a check to set expandedTopK to params.TopK if it is lower, ensuring the subquery limit is not less than the final limit. - Removed unnecessary type casting in the SQL query for embedding distance calculations, simplifying the query structure. This update improves the accuracy of vector retrieval operations in the PostgreSQL repository. --- .../repository/retriever/postgres/repository.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/internal/application/repository/retriever/postgres/repository.go b/internal/application/repository/retriever/postgres/repository.go index 3ff7796a..5d26e591 100644 --- a/internal/application/repository/retriever/postgres/repository.go +++ b/internal/application/repository/retriever/postgres/repository.go @@ -348,6 +348,9 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context, if expandedTopK > 1000 { expandedTopK = 1000 // Maximum 1000 candidates } + if expandedTopK < params.TopK { + expandedTopK = params.TopK // Ensure subquery limit is at least final limit + } // Optimized query: Use subquery to calculate distance once // Strategy: Use ORDER BY with vector distance to leverage HNSW index, @@ -364,16 +367,16 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context, FROM ( SELECT id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, - embedding::halfvec(%d) <=> $1::halfvec as distance + embedding <=> $1::halfvec as distance FROM embeddings %s - ORDER BY embedding::halfvec(%d) <=> $1::halfvec + ORDER BY embedding <=> $1::halfvec LIMIT $%d ) AS candidates WHERE distance <= $%d ORDER BY distance ASC LIMIT $%d - `, dimension, whereClause, dimension, subqueryLimitParam, thresholdParam, finalLimitParam) + `, whereClause, subqueryLimitParam, thresholdParam, finalLimitParam) allVars = append(allVars, expandedTopK) // LIMIT in subquery allVars = append(allVars, 1-params.Threshold) // Distance threshold From a560497ee89c8706ce8c8e03257d4a23256b1aaf Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 15:30:47 +0800 Subject: [PATCH 008/192] feat(tenant): add storage bucket uniqueness validation for tenant creation and updates - Implemented a new method to validate the uniqueness of storage bucket names across tenants, ensuring no two tenants can use the same bucket name. - Integrated this validation into the CreateTenant and UpdateTenant methods, enhancing data isolation and preventing potential conflicts. - Improved error logging for better traceability when validation fails. This update strengthens the integrity of tenant storage configurations. --- internal/application/service/tenant.go | 94 ++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.go index 96ee116a..1da13d8f 100644 --- a/internal/application/service/tenant.go +++ b/internal/application/service/tenant.go @@ -17,6 +17,7 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/utils" + werrors "github.com/Tencent/WeKnora/internal/errors" ) var apiKeySecret = func() []byte { @@ -58,6 +59,13 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant) tenant.CreatedAt = time.Now() tenant.UpdatedAt = time.Now() + if err := s.validateStorageBucketUniqueness(ctx, tenant); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "tenant_name": tenant.Name, + }) + return nil, err + } + logger.Info(ctx, "Saving tenant information to database") if err := s.repo.CreateTenant(ctx, tenant); err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ @@ -127,6 +135,13 @@ func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant) logger.Infof(ctx, "Updating tenant, ID: %d, name: %s", tenant.ID, tenant.Name) + if err := s.validateStorageBucketUniqueness(ctx, tenant); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "tenant_id": tenant.ID, + }) + return nil, err + } + // Generate new API key if empty if tenant.APIKey == "" { logger.Info(ctx, "API Key is empty, generating new API Key") @@ -364,3 +379,82 @@ func (s *tenantService) GetWeKnoraCloudCredentials(ctx context.Context) *types.W } return tenant.Credentials.GetWeKnoraCloud() } + +func (s *tenantService) validateStorageBucketUniqueness(ctx context.Context, tenant *types.Tenant) error { + if tenant.StorageEngineConfig == nil { + return nil + } + + // Fetch existing tenant from DB to compare + var oldTenant *types.Tenant + if tenant.ID != 0 { + var err error + oldTenant, err = s.repo.GetTenantByID(ctx, tenant.ID) + if err != nil && err.Error() != "tenant not found" && err.Error() != "record not found" { + return err + } + } + + // Fetch ALL tenants to check for collision. + allTenants, err := s.repo.ListTenants(ctx) + if err != nil { + return err + } + + // Helper to get bucket names from a StorageEngineConfig + getBuckets := func(cfg *types.StorageEngineConfig) map[string]string { + if cfg == nil { + return nil + } + res := make(map[string]string) + if cfg.MinIO != nil && cfg.MinIO.BucketName != "" { + res["minio"] = cfg.MinIO.BucketName + } + if cfg.COS != nil && cfg.COS.BucketName != "" { + res["cos"] = cfg.COS.BucketName + } + if cfg.TOS != nil && cfg.TOS.BucketName != "" { + res["tos"] = cfg.TOS.BucketName + } + if cfg.S3 != nil && cfg.S3.BucketName != "" { + res["s3"] = cfg.S3.BucketName + } + if cfg.OSS != nil && cfg.OSS.BucketName != "" { + res["oss"] = cfg.OSS.BucketName + } + return res + } + + var oldBuckets map[string]string + if oldTenant != nil { + oldBuckets = getBuckets(oldTenant.StorageEngineConfig) + } + newBuckets := getBuckets(tenant.StorageEngineConfig) + + // Collect buckets used by other tenants + usedByOthers := make(map[string]map[string]bool) // provider -> set of bucket names + for _, t := range allTenants { + if t.ID == tenant.ID { + continue + } + tb := getBuckets(t.StorageEngineConfig) + for p, b := range tb { + if usedByOthers[p] == nil { + usedByOthers[p] = make(map[string]bool) + } + usedByOthers[p][b] = true + } + } + + // Check if any NEW bucket is already used by someone else, AND it's different from the OLD bucket + for p, b := range newBuckets { + oldB := oldBuckets[p] + if b != oldB { // User is trying to change their bucket name or set a new one + if usedByOthers[p] != nil && usedByOthers[p][b] { + return werrors.NewBadRequestError("存储桶名称「" + b + "」已被其他租户使用,为保证数据隔离,请使用其他名称") + } + } + } + + return nil +} From 3e61b91efdcb3d35a78679557fcd7d94304dfd90 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 15:53:03 +0800 Subject: [PATCH 009/192] fix(storage): remove ListBucket permission from MinIO bucket policy --- docreader/parser/storage.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docreader/parser/storage.py b/docreader/parser/storage.py index 6e97838b..9ecff0cb 100644 --- a/docreader/parser/storage.py +++ b/docreader/parser/storage.py @@ -165,12 +165,9 @@ class MinioStorage(Storage): '"Version":"2012-10-17",' '"Statement":[' '{"Effect":"Allow","Principal":{"AWS":["*"]},' - '"Action":["s3:GetBucketLocation","s3:ListBucket"],' - '"Resource":["arn:aws:s3:::%s"]},' - '{"Effect":"Allow","Principal":{"AWS":["*"]},' '"Action":["s3:GetObject"],' '"Resource":["arn:aws:s3:::%s/*"]}' - "]}" % (bucket_name, bucket_name) + "]}" % (bucket_name) ) client.set_bucket_policy(bucket_name, policy) From 491c324197c772d0588f2c5b13877b0bda5a9997 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 17:32:35 +0800 Subject: [PATCH 010/192] feat(system): remove MinIO list buckets API and UI dependencies --- client/system.go | 25 - docs/docs.go | 3046 ++++++++++------- docs/swagger.json | 3046 ++++++++++------- docs/swagger.yaml | 2335 ++++++++----- frontend/src/api/system/index.ts | 14 - .../views/settings/ParserEngineSettings.vue | 678 ++-- frontend/src/views/settings/Settings.vue | 40 +- .../views/settings/StorageEngineSettings.vue | 1168 ++++--- internal/handler/system.go | 194 -- internal/router/router.go | 1 - 10 files changed, 6238 insertions(+), 4309 deletions(-) diff --git a/client/system.go b/client/system.go index b3377a8b..2e26c5f3 100644 --- a/client/system.go +++ b/client/system.go @@ -57,13 +57,6 @@ type StorageCheckResponse struct { BucketCreated bool `json:"bucket_created,omitempty"` } -// MinioBucketInfo represents MinIO bucket information -type MinioBucketInfo struct { - Name string `json:"name"` - Policy string `json:"policy"` - CreatedAt string `json:"created_at,omitempty"` -} - // GetSystemInfo gets system version and configuration information func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error) { resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/info", nil, nil) @@ -154,21 +147,3 @@ func (c *Client) CheckStorageEngine(ctx context.Context, req *StorageCheckReques } return result.Data, nil } - -// ListMinioBuckets lists all MinIO buckets with their access policies -func (c *Client) ListMinioBuckets(ctx context.Context) ([]MinioBucketInfo, error) { - resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/minio/buckets", nil, nil) - if err != nil { - return nil, err - } - var result struct { - Code int `json:"code"` - Data struct { - Buckets []MinioBucketInfo `json:"buckets"` - } `json:"data"` - } - if err := parseResponse(resp, &result); err != nil { - return nil, err - } - return result.Data.Buckets, nil -} diff --git a/docs/docs.go b/docs/docs.go index 601fe390..8e7bae98 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -51,7 +51,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -83,7 +83,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CreateAgentRequest" + "$ref": "#/definitions/handler.CreateAgentRequest" } } ], @@ -98,7 +98,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -177,13 +177,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -222,7 +222,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateAgentRequest" + "$ref": "#/definitions/handler.UpdateAgentRequest" } } ], @@ -237,13 +237,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "无法修改内置智能体", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -288,19 +288,19 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "无法删除内置智能体", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -347,13 +347,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -418,13 +418,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -455,7 +455,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } }, @@ -489,7 +489,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } ], @@ -497,7 +497,7 @@ const docTemplate = `{ "201": { "description": "Created", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "400": { @@ -535,7 +535,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } }, "404": { @@ -566,7 +566,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata" + "$ref": "#/definitions/datasource.ConnectorMetadata" } } } @@ -642,7 +642,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "404": { @@ -682,7 +682,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } ], @@ -690,7 +690,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "400": { @@ -772,7 +772,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } } }, @@ -851,7 +851,7 @@ const docTemplate = `{ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Resource" + "$ref": "#/definitions/types.Resource" } } }, @@ -925,7 +925,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } }, "400": { @@ -978,6 +978,35 @@ const docTemplate = `{ } } }, + "/auth/auto-setup": { + "post": { + "description": "Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "认证" + ], + "summary": "自动初始化(Lite 桌面版)", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/types.LoginResponse" + } + }, + "403": { + "description": "非 Lite 版本", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, "/auth/change-password": { "post": { "security": [ @@ -1026,7 +1055,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1052,7 +1081,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LoginRequest" + "$ref": "#/definitions/types.LoginRequest" } } ], @@ -1060,13 +1089,13 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LoginResponse" + "$ref": "#/definitions/types.LoginResponse" } }, "401": { "description": "认证失败", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1101,7 +1130,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1136,7 +1165,7 @@ const docTemplate = `{ "401": { "description": "未授权", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1199,7 +1228,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse" + "$ref": "#/definitions/types.OIDCConfigResponse" } } } @@ -1231,19 +1260,19 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse" + "$ref": "#/definitions/types.OIDCAuthURLResponse" } }, "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "OIDC未启用", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1289,7 +1318,7 @@ const docTemplate = `{ "401": { "description": "令牌无效", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1315,7 +1344,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterRequest" + "$ref": "#/definitions/types.RegisterRequest" } } ], @@ -1323,19 +1352,19 @@ const docTemplate = `{ "201": { "description": "Created", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterResponse" + "$ref": "#/definitions/types.RegisterResponse" } }, "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "注册功能已禁用", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1370,7 +1399,7 @@ const docTemplate = `{ "401": { "description": "令牌无效", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1417,13 +1446,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1484,13 +1513,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1551,7 +1580,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1596,7 +1625,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1644,7 +1673,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateChunkRequest" + "$ref": "#/definitions/handler.UpdateChunkRequest" } } ], @@ -1659,13 +1688,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1717,13 +1746,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1770,7 +1799,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1802,7 +1831,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.EvaluationRequest" + "$ref": "#/definitions/handler.EvaluationRequest" } } ], @@ -1817,7 +1846,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1864,7 +1893,7 @@ const docTemplate = `{ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1898,7 +1927,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.TextRelationExtractionRequest" + "$ref": "#/definitions/handler.TextRelationExtractionRequest" } } ], @@ -1913,7 +1942,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1971,7 +2000,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.FabriTextRequest" + "$ref": "#/definitions/handler.FabriTextRequest" } } ], @@ -1986,7 +2015,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2042,7 +2071,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2089,7 +2118,7 @@ const docTemplate = `{ "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2128,7 +2157,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.KBModelConfigRequest" + "$ref": "#/definitions/handler.KBModelConfigRequest" } } ], @@ -2143,13 +2172,62 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, + "/initialization/models/asr/check": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "检查ASR(语音识别)模型连接是否正常,通过发送一段静默音频测试 /v1/audio/transcriptions 端点", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "初始化" + ], + "summary": "检查ASR模型", + "parameters": [ + { + "description": "ASR检查请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "检查结果", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/errors.AppError" } } } @@ -2198,7 +2276,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2232,7 +2310,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.RemoteModelCheckRequest" + "$ref": "#/definitions/handler.RemoteModelCheckRequest" } } ], @@ -2247,7 +2325,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2296,7 +2374,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2376,7 +2454,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2455,7 +2533,7 @@ const docTemplate = `{ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2493,7 +2571,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2550,7 +2628,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2604,7 +2682,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2674,7 +2752,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2706,7 +2784,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBase" + "$ref": "#/definitions/types.KnowledgeBase" } } ], @@ -2721,7 +2799,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2755,7 +2833,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CopyKnowledgeBaseRequest" + "$ref": "#/definitions/handler.CopyKnowledgeBaseRequest" } } ], @@ -2770,7 +2848,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2817,7 +2895,7 @@ const docTemplate = `{ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2870,13 +2948,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2915,7 +2993,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateKnowledgeBaseRequest" + "$ref": "#/definitions/handler.UpdateKnowledgeBaseRequest" } } ], @@ -2930,7 +3008,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2975,7 +3053,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3058,7 +3136,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3097,7 +3175,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload" + "$ref": "#/definitions/types.FAQBatchUpsertPayload" } } ], @@ -3112,7 +3190,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3174,7 +3252,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3220,7 +3298,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3261,7 +3339,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsBatchUpdate" } } ], @@ -3276,7 +3354,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3332,7 +3410,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3386,13 +3464,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "条目不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3438,7 +3516,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } } ], @@ -3453,7 +3531,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3501,7 +3579,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.addSimilarQuestionsRequest" + "$ref": "#/definitions/handler.addSimilarQuestionsRequest" } } ], @@ -3516,13 +3594,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "条目不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3563,7 +3641,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } } ], @@ -3578,7 +3656,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3619,7 +3697,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.updateLastFAQImportResultDisplayStatusRequest" + "$ref": "#/definitions/handler.updateLastFAQImportResultDisplayStatusRequest" } } ], @@ -3634,13 +3712,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在或无导入记录", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3681,7 +3759,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQSearchRequest" + "$ref": "#/definitions/types.FAQSearchRequest" } } ], @@ -3696,7 +3774,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3737,7 +3815,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SearchParams" + "$ref": "#/definitions/types.SearchParams" } } ], @@ -3752,7 +3830,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3829,7 +3907,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3874,13 +3952,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3952,7 +4030,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "409": { @@ -4000,7 +4078,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload" + "$ref": "#/definitions/types.ManualKnowledgePayload" } } ], @@ -4015,7 +4093,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4091,7 +4169,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "409": { @@ -4145,7 +4223,7 @@ const docTemplate = `{ "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4179,7 +4257,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse" + "$ref": "#/definitions/types.ListSharesResponse" } } } @@ -4215,7 +4293,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest" + "$ref": "#/definitions/types.ShareKnowledgeBaseRequest" } } ], @@ -4275,7 +4353,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest" + "$ref": "#/definitions/types.UpdateSharePermissionRequest" } } ], @@ -4398,7 +4476,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4463,7 +4541,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4526,7 +4604,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4583,7 +4661,7 @@ const docTemplate = `{ "name": "body", "in": "body", "schema": { - "$ref": "#/definitions/internal_handler.DeleteTagRequest" + "$ref": "#/definitions/handler.DeleteTagRequest" } } ], @@ -4598,7 +4676,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4661,7 +4739,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4729,7 +4807,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4770,7 +4848,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload" + "$ref": "#/definitions/types.ManualKnowledgePayload" } } ], @@ -4785,7 +4863,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4855,7 +4933,7 @@ const docTemplate = `{ "400": { "description": "Invalid request", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4904,7 +4982,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4951,13 +5029,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4996,7 +5074,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Knowledge" + "$ref": "#/definitions/types.Knowledge" } } ], @@ -5011,7 +5089,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5056,7 +5134,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5102,7 +5180,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5151,7 +5229,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5198,13 +5276,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5242,7 +5320,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5274,7 +5352,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPService" + "$ref": "#/definitions/types.MCPService" } } ], @@ -5289,7 +5367,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5336,7 +5414,7 @@ const docTemplate = `{ "404": { "description": "服务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5390,7 +5468,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5435,7 +5513,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5482,7 +5560,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5529,7 +5607,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5576,7 +5654,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5642,7 +5720,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.SearchMessagesRequest" + "$ref": "#/definitions/handler.SearchMessagesRequest" } } ], @@ -5657,7 +5735,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5717,7 +5795,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5771,7 +5849,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5809,7 +5887,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5841,7 +5919,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CreateModelRequest" + "$ref": "#/definitions/handler.CreateModelRequest" } } ], @@ -5856,7 +5934,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5943,7 +6021,7 @@ const docTemplate = `{ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5982,7 +6060,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateModelRequest" + "$ref": "#/definitions/handler.UpdateModelRequest" } } ], @@ -5997,7 +6075,7 @@ const docTemplate = `{ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -6042,7 +6120,7 @@ const docTemplate = `{ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -6067,7 +6145,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse" + "$ref": "#/definitions/types.ListOrganizationsResponse" } } } @@ -6096,7 +6174,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest" + "$ref": "#/definitions/types.CreateOrganizationRequest" } } ], @@ -6142,7 +6220,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest" + "$ref": "#/definitions/types.JoinOrganizationRequest" } } ], @@ -6188,7 +6266,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest" + "$ref": "#/definitions/types.JoinByOrganizationIDRequest" } } ], @@ -6234,7 +6312,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest" + "$ref": "#/definitions/types.SubmitJoinRequestRequest" } } ], @@ -6408,7 +6486,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest" + "$ref": "#/definitions/types.UpdateOrganizationRequest" } } ], @@ -6497,7 +6575,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.InviteMemberRequest" + "$ref": "#/definitions/types.InviteMemberRequest" } } ], @@ -6645,7 +6723,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest" + "$ref": "#/definitions/types.ReviewJoinRequestRequest" } } ], @@ -6732,7 +6810,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListMembersResponse" + "$ref": "#/definitions/types.ListMembersResponse" } } } @@ -6777,7 +6855,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest" + "$ref": "#/definitions/types.UpdateMemberRoleRequest" } } ], @@ -6873,7 +6951,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest" + "$ref": "#/definitions/types.RequestRoleUpgradeRequest" } } ], @@ -7047,7 +7125,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse" + "$ref": "#/definitions/types.ListSharesResponse" } } } @@ -7099,7 +7177,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7131,7 +7209,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateSessionRequest" + "$ref": "#/definitions/handler_session.CreateSessionRequest" } } ], @@ -7146,7 +7224,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7180,7 +7258,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.batchDeleteRequest" + "$ref": "#/definitions/handler_session.batchDeleteRequest" } } ], @@ -7195,7 +7273,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7229,7 +7307,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.SearchKnowledgeRequest" + "$ref": "#/definitions/handler_session.SearchKnowledgeRequest" } } ], @@ -7244,7 +7322,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7291,7 +7369,7 @@ const docTemplate = `{ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7330,7 +7408,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Session" + "$ref": "#/definitions/types.Session" } } ], @@ -7345,7 +7423,7 @@ const docTemplate = `{ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7390,7 +7468,7 @@ const docTemplate = `{ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7437,13 +7515,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7484,7 +7562,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateKnowledgeQARequest" + "$ref": "#/definitions/handler_session.CreateKnowledgeQARequest" } } ], @@ -7499,7 +7577,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7553,7 +7631,7 @@ const docTemplate = `{ "404": { "description": "会话或消息不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7594,7 +7672,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateKnowledgeQARequest" + "$ref": "#/definitions/handler_session.CreateKnowledgeQARequest" } } ], @@ -7609,7 +7687,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7650,7 +7728,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.StopSessionRequest" + "$ref": "#/definitions/handler_session.StopSessionRequest" } } ], @@ -7665,7 +7743,7 @@ const docTemplate = `{ "404": { "description": "会话或消息不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7706,7 +7784,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.GenerateTitleRequest" + "$ref": "#/definitions/handler_session.GenerateTitleRequest" } } ], @@ -7721,7 +7799,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7785,7 +7863,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7838,44 +7916,7 @@ const docTemplate = `{ "200": { "description": "系统信息", "schema": { - "$ref": "#/definitions/internal_handler.GetSystemInfoResponse" - } - } - } - } - }, - "/system/minio/buckets": { - "get": { - "description": "获取所有 MinIO 存储桶及其访问权限", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "系统" - ], - "summary": "列出 MinIO 存储桶", - "responses": { - "200": { - "description": "存储桶列表", - "schema": { - "$ref": "#/definitions/internal_handler.ListMinioBucketsResponse" - } - }, - "400": { - "description": "MinIO 未启用", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "500": { - "description": "服务器错误", - "schema": { - "type": "object", - "additionalProperties": true + "$ref": "#/definitions/handler.GetSystemInfoResponse" } } } @@ -7951,7 +7992,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.StorageCheckRequest" + "$ref": "#/definitions/handler.StorageCheckRequest" } } ], @@ -7959,7 +8000,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/internal_handler.StorageCheckResponse" + "$ref": "#/definitions/handler.StorageCheckResponse" } } } @@ -7979,7 +8020,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/internal_handler.GetStorageEngineStatusResponse" + "$ref": "#/definitions/handler.GetStorageEngineStatusResponse" } } } @@ -8014,7 +8055,7 @@ const docTemplate = `{ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8043,7 +8084,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } } ], @@ -8058,7 +8099,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8093,7 +8134,7 @@ const docTemplate = `{ "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8131,7 +8172,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8169,7 +8210,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8207,7 +8248,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8245,7 +8286,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8292,7 +8333,7 @@ const docTemplate = `{ "400": { "description": "不支持的键", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8346,7 +8387,7 @@ const docTemplate = `{ "400": { "description": "不支持的键", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8412,7 +8453,7 @@ const docTemplate = `{ "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8459,13 +8500,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "租户不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8501,7 +8542,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } } ], @@ -8516,7 +8557,7 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8558,13 +8599,13 @@ const docTemplate = `{ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } } }, - "/web-search/providers": { + "/vector-stores": { "get": { "security": [ { @@ -8574,7 +8615,41 @@ const docTemplate = `{ "ApiKeyAuth": [] } ], - "description": "Returns the list of available web search providers from configuration", + "description": "List all vector stores for the current tenant, including environment-configured and user-created stores", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "List vector stores", + "responses": { + "200": { + "description": "List of vector stores (env + DB)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Create a new vector store configuration for the current tenant", "consumes": [ "application/json" ], @@ -8582,12 +8657,349 @@ const docTemplate = `{ "application/json" ], "tags": [ - "web-search" + "VectorStore" + ], + "summary": "Create vector store", + "parameters": [ + { + "description": "Vector store configuration", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.CreateStoreRequest" + } + } + ], + "responses": { + "201": { + "description": "Created vector store", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid request or validation error", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "409": { + "description": "Duplicate endpoint and index", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, + "/vector-stores/test": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Test connectivity using provided credentials without persisting. Returns detected server version.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Test vector store connection with raw credentials", + "parameters": [ + { + "description": "Engine type and connection config", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.TestStoreRequest" + } + } ], - "summary": "Get available web search providers", "responses": { "200": { - "description": "List of providers", + "description": "Connection test result (success, version)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/types": { + "get": { + "description": "Return supported engine types with connection and index field schemas for UI form generation", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "List vector store types", + "responses": { + "200": { + "description": "List of engine types with config schemas", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/{id}": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Retrieve a single vector store by ID. Supports both DB stores and env stores (__env_* IDs)", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Get vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Vector store details", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "put": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Update a vector store (name only). Engine type, connection config, and index config are immutable. Env stores cannot be modified.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Update vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Updated fields", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.UpdateStoreRequest" + } + } + ], + "responses": { + "200": { + "description": "Updated vector store", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Env store or validation error", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "delete": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Soft-delete a vector store. Env stores cannot be deleted.", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Delete vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Deletion success", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Env store cannot be deleted", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/{id}/test": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Test connectivity of an existing saved or env store. Returns detected server version. For DB stores, the version is automatically saved to connection_config.", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Test vector store connection by ID", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Connection test result (success, version)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", "schema": { "type": "object", "additionalProperties": true @@ -8598,7 +9010,7 @@ const docTemplate = `{ } }, "definitions": { - "github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata": { + "datasource.ConnectorMetadata": { "type": "object", "properties": { "auth_type": { @@ -8630,11 +9042,11 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_errors.AppError": { + "errors.AppError": { "type": "object", "properties": { "code": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.ErrorCode" + "$ref": "#/definitions/errors.ErrorCode" }, "details": {}, "message": { @@ -8642,7 +9054,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_errors.ErrorCode": { + "errors.ErrorCode": { "type": "integer", "enum": [ 1000, @@ -8689,7 +9101,814 @@ const docTemplate = `{ "ErrAgentInvalidTemperature" ] }, - "github_com_Tencent_WeKnora_internal_types.AgentConfig": { + "github_com_Tencent_WeKnora_internal_errors.AppError": { + "type": "object", + "properties": { + "code": { + "$ref": "#/definitions/errors.ErrorCode" + }, + "details": {}, + "message": { + "type": "string" + } + } + }, + "gorm.DeletedAt": { + "type": "object", + "properties": { + "time": { + "type": "string" + }, + "valid": { + "description": "Valid is true if Time is not NULL", + "type": "boolean" + } + } + }, + "handler.CopyKnowledgeBaseRequest": { + "type": "object", + "required": [ + "source_id" + ], + "properties": { + "source_id": { + "type": "string" + }, + "target_id": { + "type": "string" + }, + "task_id": { + "type": "string" + } + } + }, + "handler.CreateAgentRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "avatar": { + "type": "string" + }, + "config": { + "$ref": "#/definitions/types.CustomAgentConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.CreateModelRequest": { + "type": "object", + "required": [ + "name", + "parameters", + "source", + "type" + ], + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "parameters": { + "$ref": "#/definitions/types.ModelParameters" + }, + "source": { + "$ref": "#/definitions/types.ModelSource" + }, + "type": { + "$ref": "#/definitions/types.ModelType" + } + } + }, + "handler.CreateStoreRequest": { + "type": "object", + "required": [ + "connection_config", + "engine_type", + "name" + ], + "properties": { + "connection_config": { + "$ref": "#/definitions/types.ConnectionConfig" + }, + "engine_type": { + "$ref": "#/definitions/types.RetrieverEngineType" + }, + "index_config": { + "$ref": "#/definitions/types.IndexConfig" + }, + "name": { + "type": "string" + } + } + }, + "handler.DeleteTagRequest": { + "type": "object", + "properties": { + "exclude_ids": { + "description": "Chunk seq_ids to exclude from deletion", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "handler.EvaluationRequest": { + "type": "object", + "properties": { + "chat_id": { + "description": "ID of chat model to use", + "type": "string" + }, + "dataset_id": { + "description": "ID of dataset to evaluate", + "type": "string" + }, + "knowledge_base_id": { + "description": "ID of knowledge base to use", + "type": "string" + }, + "rerank_id": { + "description": "ID of rerank model to use", + "type": "string" + } + } + }, + "handler.FabriTextRequest": { + "type": "object", + "required": [ + "model_id" + ], + "properties": { + "model_id": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "handler.GetStorageEngineStatusResponse": { + "type": "object", + "properties": { + "engines": { + "type": "array", + "items": { + "$ref": "#/definitions/handler.StorageEngineStatusItem" + } + }, + "minio_env_available": { + "type": "boolean" + } + } + }, + "handler.GetSystemInfoResponse": { + "type": "object", + "properties": { + "build_time": { + "type": "string" + }, + "commit_id": { + "type": "string" + }, + "db_version": { + "type": "string" + }, + "edition": { + "type": "string" + }, + "go_version": { + "type": "string" + }, + "graph_database_engine": { + "type": "string" + }, + "keyword_index_engine": { + "type": "string" + }, + "minio_enabled": { + "type": "boolean" + }, + "vector_store_engine": { + "type": "string" + }, + "version": { + "type": "string" + } + } + }, + "handler.KBModelConfigRequest": { + "type": "object", + "required": [ + "embeddingModelId", + "llmModelId" + ], + "properties": { + "asr_config": { + "$ref": "#/definitions/types.ASRConfig" + }, + "documentSplitting": { + "description": "文档分块配置", + "type": "object", + "properties": { + "childChunkSize": { + "type": "integer" + }, + "chunkOverlap": { + "type": "integer" + }, + "chunkSize": { + "type": "integer" + }, + "enableParentChild": { + "type": "boolean" + }, + "parentChunkSize": { + "type": "integer" + }, + "parserEngineRules": { + "type": "array", + "items": { + "$ref": "#/definitions/types.ParserEngineRule" + } + }, + "separators": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "embeddingModelId": { + "type": "string" + }, + "llmModelId": { + "type": "string" + }, + "multimodal": { + "description": "多模态配置(仅模型相关;存储引擎在 storageProvider 中配置)", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + } + }, + "nodeExtract": { + "description": "知识图谱配置", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "nodes": { + "type": "array", + "items": { + "$ref": "#/definitions/types.GraphNode" + } + }, + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/types.GraphRelation" + } + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + } + }, + "questionGeneration": { + "description": "问题生成配置", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "questionCount": { + "type": "integer" + } + } + }, + "storageProvider": { + "description": "存储引擎选择(\"local\" | \"minio\" | \"cos\"),影响文档上传与文档内图片存储,参数从全局设置读取", + "type": "string" + }, + "vlm_config": { + "$ref": "#/definitions/types.VLMConfig" + } + } + }, + "handler.RemoteModelCheckRequest": { + "type": "object", + "required": [ + "baseUrl", + "modelName" + ], + "properties": { + "apiKey": { + "type": "string" + }, + "baseUrl": { + "type": "string" + }, + "modelName": { + "type": "string" + }, + "provider": { + "type": "string" + } + } + }, + "handler.SearchMessagesRequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "limit": { + "description": "Maximum number of results to return (default: 20)", + "type": "integer" + }, + "mode": { + "description": "Search mode: \"keyword\", \"vector\", \"hybrid\" (default: \"hybrid\")", + "type": "string" + }, + "query": { + "description": "Query text for search", + "type": "string" + }, + "session_ids": { + "description": "Filter by specific session IDs (optional)", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "handler.StorageCheckRequest": { + "type": "object", + "properties": { + "cos": { + "$ref": "#/definitions/types.COSEngineConfig" + }, + "minio": { + "$ref": "#/definitions/types.MinIOEngineConfig" + }, + "oss": { + "$ref": "#/definitions/types.OSSEngineConfig" + }, + "provider": { + "description": "\"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", + "type": "string" + }, + "s3": { + "$ref": "#/definitions/types.S3EngineConfig" + }, + "tos": { + "$ref": "#/definitions/types.TOSEngineConfig" + } + } + }, + "handler.StorageCheckResponse": { + "type": "object", + "properties": { + "bucket_created": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "ok": { + "type": "boolean" + } + } + }, + "handler.StorageEngineStatusItem": { + "type": "object", + "properties": { + "available": { + "description": "whether the engine can be used", + "type": "boolean" + }, + "description": { + "description": "short description for UI", + "type": "string" + }, + "name": { + "description": "\"local\", \"minio\", \"cos\", \"tos\"", + "type": "string" + } + } + }, + "handler.TestStoreRequest": { + "type": "object", + "required": [ + "connection_config", + "engine_type" + ], + "properties": { + "connection_config": { + "$ref": "#/definitions/types.ConnectionConfig" + }, + "engine_type": { + "$ref": "#/definitions/types.RetrieverEngineType" + } + } + }, + "handler.TextRelationExtractionRequest": { + "type": "object", + "required": [ + "model_id", + "tags", + "text" + ], + "properties": { + "model_id": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + } + }, + "handler.UpdateAgentRequest": { + "type": "object", + "properties": { + "avatar": { + "type": "string" + }, + "config": { + "$ref": "#/definitions/types.CustomAgentConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.UpdateChunkRequest": { + "type": "object", + "properties": { + "chunk_index": { + "type": "integer" + }, + "content": { + "type": "string" + }, + "embedding": { + "type": "array", + "items": { + "type": "number" + } + }, + "end_at": { + "type": "integer" + }, + "image_info": { + "type": "string" + }, + "is_enabled": { + "type": "boolean" + }, + "start_at": { + "type": "integer" + } + } + }, + "handler.UpdateKnowledgeBaseRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "config": { + "$ref": "#/definitions/types.KnowledgeBaseConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.UpdateModelRequest": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "parameters": { + "$ref": "#/definitions/types.ModelParameters" + }, + "source": { + "$ref": "#/definitions/types.ModelSource" + }, + "type": { + "$ref": "#/definitions/types.ModelType" + } + } + }, + "handler.UpdateStoreRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + } + } + }, + "handler.addSimilarQuestionsRequest": { + "type": "object", + "required": [ + "similar_questions" + ], + "properties": { + "similar_questions": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + } + } + } + }, + "handler.updateLastFAQImportResultDisplayStatusRequest": { + "type": "object", + "required": [ + "display_status" + ], + "properties": { + "display_status": { + "type": "string", + "enum": [ + "open", + "close" + ] + } + } + }, + "handler_session.AttachmentUpload": { + "type": "object", + "properties": { + "data": { + "description": "Base64-encoded file content", + "type": "string" + }, + "file_name": { + "description": "Original filename", + "type": "string" + }, + "file_size": { + "description": "File size in bytes", + "type": "integer" + } + } + }, + "handler_session.CreateKnowledgeQARequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "agent_enabled": { + "description": "Whether agent mode is enabled for this request", + "type": "boolean" + }, + "agent_id": { + "description": "Selected custom agent ID (backend resolves shared agent and its tenant from share relation)", + "type": "string" + }, + "attachment_uploads": { + "description": "Attached files (documents, audio, etc.)", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.AttachmentUpload" + } + }, + "channel": { + "description": "Source channel: \"web\", \"api\", \"im\", etc.", + "type": "string" + }, + "disable_title": { + "description": "Whether to disable auto title generation", + "type": "boolean" + }, + "enable_memory": { + "description": "Whether memory feature is enabled for this request", + "type": "boolean" + }, + "images": { + "description": "Attached images for multimodal chat", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.ImageAttachment" + } + }, + "knowledge_base_ids": { + "description": "Selected knowledge base ID for this request", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_ids": { + "description": "Selected knowledge ID for this request", + "type": "array", + "items": { + "type": "string" + } + }, + "mentioned_items": { + "description": "@mentioned knowledge bases and files", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.MentionedItemRequest" + } + }, + "query": { + "description": "Query text for knowledge base search", + "type": "string" + }, + "summary_model_id": { + "description": "Optional summary model ID for this request (overrides session default)", + "type": "string" + }, + "web_search_enabled": { + "description": "Whether web search is enabled for this request", + "type": "boolean" + } + } + }, + "handler_session.CreateSessionRequest": { + "type": "object", + "properties": { + "description": { + "description": "Description for the session (optional)", + "type": "string" + }, + "title": { + "description": "Title for the session (optional)", + "type": "string" + } + } + }, + "handler_session.GenerateTitleRequest": { + "type": "object", + "required": [ + "messages" + ], + "properties": { + "messages": { + "description": "Messages to use as context for title generation", + "type": "array", + "items": { + "$ref": "#/definitions/types.Message" + } + } + } + }, + "handler_session.ImageAttachment": { + "type": "object", + "properties": { + "caption": { + "description": "VLM analysis result (context-aware, single call)", + "type": "string" + }, + "data": { + "description": "base64 data URI from frontend (data:image/png;base64,...)", + "type": "string" + }, + "url": { + "description": "serving URL after saving to storage", + "type": "string" + } + } + }, + "handler_session.MentionedItemRequest": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kb_type": { + "description": "\"document\" or \"faq\" (only for kb type)", + "type": "string" + }, + "name": { + "type": "string" + }, + "type": { + "description": "\"kb\" for knowledge base, \"file\" for file", + "type": "string" + } + } + }, + "handler_session.SearchKnowledgeRequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "knowledge_base_id": { + "description": "Single knowledge base ID (for backward compatibility)", + "type": "string" + }, + "knowledge_base_ids": { + "description": "IDs of knowledge bases to search (multi-KB support)", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_ids": { + "description": "IDs of specific knowledge (files) to search", + "type": "array", + "items": { + "type": "string" + } + }, + "query": { + "description": "Query text to search for", + "type": "string" + } + } + }, + "handler_session.StopSessionRequest": { + "type": "object", + "required": [ + "message_id" + ], + "properties": { + "message_id": { + "type": "string" + } + } + }, + "handler_session.batchDeleteRequest": { + "type": "object", + "properties": { + "delete_all": { + "type": "boolean" + }, + "ids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "types.ASRConfig": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "language": { + "description": "optional: language hint for transcription", + "type": "string" + }, + "model_id": { + "type": "string" + } + } + }, + "types.AgentConfig": { "type": "object", "properties": { "allowed_skills": { @@ -8805,10 +10024,14 @@ const docTemplate = `{ "web_search_max_results": { "description": "Maximum number of web search results (default: 5)", "type": "integer" + }, + "web_search_provider_id": { + "description": "WebSearchProviderEntity ID (resolved from agent config)", + "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.AgentStep": { + "types.AgentStep": { "type": "object", "properties": { "iteration": { @@ -8827,12 +10050,12 @@ const docTemplate = `{ "description": "Tools called in this step (Act phase)", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall" + "$ref": "#/definitions/types.ToolCall" } } } }, - "github_com_Tencent_WeKnora_internal_types.AnswerStrategy": { + "types.AnswerStrategy": { "type": "string", "enum": [ "all", @@ -8843,7 +10066,7 @@ const docTemplate = `{ "AnswerStrategyRandom" ] }, - "github_com_Tencent_WeKnora_internal_types.COSEngineConfig": { + "types.COSEngineConfig": { "type": "object", "properties": { "app_id": { @@ -8866,7 +10089,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig": { + "types.ChatHistoryConfig": { "type": "object", "properties": { "embedding_model_id": { @@ -8883,7 +10106,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ChunkingConfig": { + "types.ChunkingConfig": { "type": "object", "properties": { "child_chunk_size": { @@ -8914,7 +10137,7 @@ const docTemplate = `{ "description": "ParserEngineRules configures which parser engine to use for each file type.\nWhen empty, the builtin engine is used for all types.", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule" + "$ref": "#/definitions/types.ParserEngineRule" } }, "separators": { @@ -8926,7 +10149,52 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy": { + "types.ConnectionConfig": { + "type": "object", + "properties": { + "addr": { + "description": "Common", + "type": "string" + }, + "api_key": { + "description": "AES-GCM encrypted", + "type": "string" + }, + "grpc_address": { + "description": "Weaviate", + "type": "string" + }, + "host": { + "description": "Qdrant", + "type": "string" + }, + "password": { + "description": "AES-GCM encrypted", + "type": "string" + }, + "port": { + "type": "integer" + }, + "scheme": { + "type": "string" + }, + "use_default_connection": { + "description": "Postgres", + "type": "boolean" + }, + "use_tls": { + "type": "boolean" + }, + "username": { + "type": "string" + }, + "version": { + "description": "Version is the detected server version (e.g., \"7.10.1\", \"16.2\", \"1.12.6\").\nAuto-populated by TestConnection on successful connectivity check.", + "type": "string" + } + } + }, + "types.ContextCompressionStrategy": { "type": "string", "enum": [ "sliding_window", @@ -8937,14 +10205,14 @@ const docTemplate = `{ "ContextCompressionSmart" ] }, - "github_com_Tencent_WeKnora_internal_types.ContextConfig": { + "types.ContextConfig": { "type": "object", "properties": { "compression_strategy": { "description": "Compression strategy: \"sliding_window\" or \"smart\"", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy" + "$ref": "#/definitions/types.ContextCompressionStrategy" } ] }, @@ -8962,7 +10230,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ConversationConfig": { + "types.ConversationConfig": { "type": "object", "properties": { "context_template": { @@ -9032,7 +10300,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest": { + "types.CreateOrganizationRequest": { "type": "object", "required": [ "name" @@ -9062,7 +10330,15 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.CustomAgentConfig": { + "types.CredentialsConfig": { + "type": "object", + "properties": { + "weknoracloud": { + "$ref": "#/definitions/types.WeKnoraCloudCredentials" + } + } + }, + "types.CustomAgentConfig": { "type": "object", "properties": { "agent_mode": { @@ -9076,6 +10352,14 @@ const docTemplate = `{ "type": "string" } }, + "asr_model_id": { + "description": "ASR model ID for audio transcription (optional)", + "type": "string" + }, + "audio_upload_enabled": { + "description": "Whether audio upload (ASR transcription) is enabled for this agent (default: false)", + "type": "boolean" + }, "context_template": { "description": "Context template for normal mode (how to format retrieved chunks)", "type": "string" @@ -9147,6 +10431,10 @@ const docTemplate = `{ "type": "string" } }, + "llm_call_timeout": { + "description": "Timeout for a single LLM call in seconds (0 = use global default)", + "type": "integer" + }, "max_completion_tokens": { "description": "Maximum completion tokens (only for normal mode)", "type": "integer" @@ -9247,6 +10535,14 @@ const docTemplate = `{ "description": "VLM model ID for image analysis (optional, falls back to tenant-level VLM)", "type": "string" }, + "web_fetch_enabled": { + "description": "Whether to auto-fetch full page content for reranked web search results", + "type": "boolean" + }, + "web_fetch_top_n": { + "description": "Max number of pages to fetch after rerank (default: 3)", + "type": "integer" + }, "web_search_enabled": { "description": "===== Web Search Settings =====\nWhether web search is enabled", "type": "boolean" @@ -9254,10 +10550,14 @@ const docTemplate = `{ "web_search_max_results": { "description": "Maximum web search results", "type": "integer" + }, + "web_search_provider_id": { + "description": "WebSearchProviderID references a specific WebSearchProviderEntity.\nIf empty, the tenant's default provider (is_default=true) is used.", + "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.DataSource": { + "types.DataSource": { "type": "object", "properties": { "config": { @@ -9317,7 +10617,7 @@ const docTemplate = `{ "description": "Latest sync log (not stored in DB, populated on query)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } ] }, @@ -9363,7 +10663,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.EmbeddingParameters": { + "types.EmbeddingParameters": { "type": "object", "properties": { "dimension": { @@ -9374,7 +10674,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ExtractConfig": { + "types.ExtractConfig": { "type": "object", "properties": { "enabled": { @@ -9383,13 +10683,13 @@ const docTemplate = `{ "nodes": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode" + "$ref": "#/definitions/types.GraphNode" } }, "relations": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation" + "$ref": "#/definitions/types.GraphRelation" } }, "tags": { @@ -9403,7 +10703,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload": { + "types.FAQBatchUpsertPayload": { "type": "object", "required": [ "entries" @@ -9416,7 +10716,7 @@ const docTemplate = `{ "entries": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } }, "knowledge_id": { @@ -9435,32 +10735,32 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQConfig": { + "types.FAQConfig": { "type": "object", "properties": { "index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + "$ref": "#/definitions/types.FAQIndexMode" }, "question_index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + "$ref": "#/definitions/types.FAQQuestionIndexMode" } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate": { + "types.FAQEntryFieldsBatchUpdate": { "type": "object", "properties": { "by_id": { "description": "ByID 按条目ID更新,key为条目ID (seq_id)", "type": "object", "additionalProperties": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsUpdate" } }, "by_tag": { "description": "ByTag 按Tag批量更新,key为TagID (seq_id)", "type": "object", "additionalProperties": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsUpdate" } }, "exclude_ids": { @@ -9472,7 +10772,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate": { + "types.FAQEntryFieldsUpdate": { "type": "object", "properties": { "is_enabled": { @@ -9486,14 +10786,14 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryPayload": { + "types.FAQEntryPayload": { "type": "object", "required": [ "standard_question" ], "properties": { "answer_strategy": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AnswerStrategy" + "$ref": "#/definitions/types.AnswerStrategy" }, "answers": { "type": "array", @@ -9534,7 +10834,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQIndexMode": { + "types.FAQIndexMode": { "type": "string", "enum": [ "question_only", @@ -9545,7 +10845,7 @@ const docTemplate = `{ "FAQIndexModeQuestionAnswer" ] }, - "github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode": { + "types.FAQQuestionIndexMode": { "type": "string", "enum": [ "combined", @@ -9556,7 +10856,7 @@ const docTemplate = `{ "FAQQuestionIndexModeSeparate" ] }, - "github_com_Tencent_WeKnora_internal_types.FAQSearchRequest": { + "types.FAQSearchRequest": { "type": "object", "required": [ "query_text" @@ -9591,7 +10891,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.GraphNode": { + "types.GraphNode": { "type": "object", "properties": { "attributes": { @@ -9611,7 +10911,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.GraphRelation": { + "types.GraphRelation": { "type": "object", "properties": { "node1": { @@ -9625,7 +10925,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig": { + "types.ImageProcessingConfig": { "type": "object", "properties": { "model_id": { @@ -9634,7 +10934,32 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.InviteMemberRequest": { + "types.IndexConfig": { + "type": "object", + "properties": { + "collection_name": { + "description": "Milvus", + "type": "string" + }, + "collection_prefix": { + "description": "Qdrant", + "type": "string" + }, + "index_name": { + "description": "ES, OpenSearch", + "type": "string" + }, + "number_of_replicas": { + "description": "ES, OpenSearch", + "type": "integer" + }, + "number_of_shards": { + "description": "ES, OpenSearch", + "type": "integer" + } + } + }, + "types.InviteMemberRequest": { "type": "object", "required": [ "role", @@ -9645,7 +10970,7 @@ const docTemplate = `{ "description": "Role to assign: admin/editor/viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] }, @@ -9655,7 +10980,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest": { + "types.JoinByOrganizationIDRequest": { "type": "object", "required": [ "organization_id" @@ -9673,13 +10998,13 @@ const docTemplate = `{ "description": "Optional: requested role (admin/editor/viewer); default viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest": { + "types.JoinOrganizationRequest": { "type": "object", "required": [ "invite_code" @@ -9692,7 +11017,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.Knowledge": { + "types.Knowledge": { "type": "object", "properties": { "channel": { @@ -9815,9 +11140,17 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBase": { + "types.KnowledgeBase": { "type": "object", "properties": { + "asr_config": { + "description": "ASR config (Automatic Speech Recognition)", + "allOf": [ + { + "$ref": "#/definitions/types.ASRConfig" + } + ] + }, "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer" @@ -9826,7 +11159,7 @@ const docTemplate = `{ "description": "Chunking configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + "$ref": "#/definitions/types.ChunkingConfig" } ] }, @@ -9854,7 +11187,7 @@ const docTemplate = `{ "description": "Extract config", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + "$ref": "#/definitions/types.ExtractConfig" } ] }, @@ -9862,7 +11195,7 @@ const docTemplate = `{ "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + "$ref": "#/definitions/types.FAQConfig" } ] }, @@ -9874,7 +11207,7 @@ const docTemplate = `{ "description": "Image processing configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + "$ref": "#/definitions/types.ImageProcessingConfig" } ] }, @@ -9910,7 +11243,7 @@ const docTemplate = `{ "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + "$ref": "#/definitions/types.QuestionGenerationConfig" } ] }, @@ -9922,7 +11255,7 @@ const docTemplate = `{ "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageConfig" + "$ref": "#/definitions/types.StorageConfig" } ] }, @@ -9930,7 +11263,7 @@ const docTemplate = `{ "description": "Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageProviderConfig" + "$ref": "#/definitions/types.StorageProviderConfig" } ] }, @@ -9954,20 +11287,20 @@ const docTemplate = `{ "description": "VLM config", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" + "$ref": "#/definitions/types.VLMConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig": { + "types.KnowledgeBaseConfig": { "type": "object", "properties": { "chunking_config": { "description": "Chunking configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + "$ref": "#/definitions/types.ChunkingConfig" } ] }, @@ -9975,7 +11308,7 @@ const docTemplate = `{ "description": "FAQ configuration (only for FAQ type knowledge bases)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + "$ref": "#/definitions/types.FAQConfig" } ] }, @@ -9983,13 +11316,13 @@ const docTemplate = `{ "description": "Image processing configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + "$ref": "#/definitions/types.ImageProcessingConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse": { + "types.KnowledgeBaseShareResponse": { "type": "object", "properties": { "chunk_count": { @@ -10045,13 +11378,13 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ListMembersResponse": { + "types.ListMembersResponse": { "type": "object", "properties": { "members": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse" + "$ref": "#/definitions/types.OrganizationMemberResponse" } }, "total": { @@ -10059,20 +11392,20 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse": { + "types.ListOrganizationsResponse": { "type": "object", "properties": { "organizations": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationResponse" + "$ref": "#/definitions/types.OrganizationResponse" } }, "resource_counts": { "description": "各空间内知识库/智能体数量,供列表侧栏展示", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse" + "$ref": "#/definitions/types.ResourceCountsByOrgResponse" } ] }, @@ -10081,13 +11414,13 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ListSharesResponse": { + "types.ListSharesResponse": { "type": "object", "properties": { "shares": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse" + "$ref": "#/definitions/types.KnowledgeBaseShareResponse" } }, "total": { @@ -10095,7 +11428,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.LocalEngineConfig": { + "types.LocalEngineConfig": { "type": "object", "properties": { "path_prefix": { @@ -10103,7 +11436,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.LoginRequest": { + "types.LoginRequest": { "type": "object", "required": [ "email", @@ -10119,7 +11452,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.LoginResponse": { + "types.LoginResponse": { "type": "object", "properties": { "message": { @@ -10132,17 +11465,17 @@ const docTemplate = `{ "type": "boolean" }, "tenant": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" }, "token": { "type": "string" }, "user": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.User" + "$ref": "#/definitions/types.User" } } }, - "github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig": { + "types.MCPAdvancedConfig": { "type": "object", "properties": { "retry_count": { @@ -10159,7 +11492,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPAuthConfig": { + "types.MCPAuthConfig": { "type": "object", "properties": { "api_key": { @@ -10176,26 +11509,26 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPEnvVars": { + "types.MCPEnvVars": { "type": "object", "additionalProperties": { "type": "string" } }, - "github_com_Tencent_WeKnora_internal_types.MCPHeaders": { + "types.MCPHeaders": { "type": "object", "additionalProperties": { "type": "string" } }, - "github_com_Tencent_WeKnora_internal_types.MCPService": { + "types.MCPService": { "type": "object", "properties": { "advanced_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig" + "$ref": "#/definitions/types.MCPAdvancedConfig" }, "auth_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAuthConfig" + "$ref": "#/definitions/types.MCPAuthConfig" }, "created_at": { "type": "string" @@ -10213,12 +11546,12 @@ const docTemplate = `{ "description": "Environment variables for stdio", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPEnvVars" + "$ref": "#/definitions/types.MCPEnvVars" } ] }, "headers": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPHeaders" + "$ref": "#/definitions/types.MCPHeaders" }, "id": { "type": "string" @@ -10234,7 +11567,7 @@ const docTemplate = `{ "description": "Required for stdio transport", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPStdioConfig" + "$ref": "#/definitions/types.MCPStdioConfig" } ] }, @@ -10242,7 +11575,7 @@ const docTemplate = `{ "type": "integer" }, "transport_type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPTransportType" + "$ref": "#/definitions/types.MCPTransportType" }, "updated_at": { "type": "string" @@ -10253,7 +11586,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPStdioConfig": { + "types.MCPStdioConfig": { "type": "object", "properties": { "args": { @@ -10269,7 +11602,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPTransportType": { + "types.MCPTransportType": { "type": "string", "enum": [ "sse", @@ -10292,7 +11625,7 @@ const docTemplate = `{ "MCPTransportStdio" ] }, - "github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload": { + "types.ManualKnowledgePayload": { "type": "object", "properties": { "channel": { @@ -10312,7 +11645,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MatchType": { + "types.MatchType": { "type": "integer", "enum": [ 0, @@ -10358,7 +11691,7 @@ const docTemplate = `{ "MatchTypeDataAnalysis" ] }, - "github_com_Tencent_WeKnora_internal_types.MentionedItem": { + "types.MentionedItem": { "type": "object", "properties": { "id": { @@ -10377,7 +11710,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.Message": { + "types.Message": { "type": "object", "properties": { "agent_duration_ms": { @@ -10388,7 +11721,14 @@ const docTemplate = `{ "description": "Agent execution steps (only for assistant messages generated by agent)\nThis contains the detailed reasoning process and tool calls made by the agent\nStored for user history display, but NOT included in LLM context to avoid redundancy", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AgentStep" + "$ref": "#/definitions/types.AgentStep" + } + }, + "attachments": { + "description": "Attached files (documents, audio, etc., for user messages)", + "type": "array", + "items": { + "$ref": "#/definitions/types.MessageAttachment" } }, "channel": { @@ -10419,7 +11759,7 @@ const docTemplate = `{ "description": "Attached images with OCR/Caption text (for user messages)", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MessageImage" + "$ref": "#/definitions/types.MessageImage" } }, "is_completed": { @@ -10438,14 +11778,14 @@ const docTemplate = `{ "description": "References to knowledge chunks used in the response", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SearchResult" + "$ref": "#/definitions/types.SearchResult" } }, "mentioned_items": { "description": "Mentioned knowledge bases and files (for user messages)\nStores the @mentioned items when user sends a message", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem" + "$ref": "#/definitions/types.MentionedItem" } }, "request_id": { @@ -10466,7 +11806,40 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MessageImage": { + "types.MessageAttachment": { + "type": "object", + "properties": { + "content": { + "description": "Extracted text content (for small text files)", + "type": "string" + }, + "file_name": { + "description": "Original filename", + "type": "string" + }, + "file_size": { + "description": "File size in bytes", + "type": "integer" + }, + "file_type": { + "description": "File extension (e.g., \".pdf\", \".docx\")", + "type": "string" + }, + "is_truncated": { + "description": "Whether content was truncated", + "type": "boolean" + }, + "line_count": { + "description": "Total line count (for text files)", + "type": "integer" + }, + "url": { + "description": "Storage URL (provider://path)", + "type": "string" + } + } + }, + "types.MessageImage": { "type": "object", "properties": { "caption": { @@ -10477,7 +11850,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig": { + "types.MinIOEngineConfig": { "type": "object", "properties": { "access_key_id": { @@ -10504,17 +11877,25 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ModelParameters": { + "types.ModelParameters": { "type": "object", "properties": { "api_key": { "type": "string" }, + "app_id": { + "description": "WeKnoraCloud 厂商专用凭证", + "type": "string" + }, + "app_secret": { + "description": "AES-256 加密存储,实际承载上游 API Key", + "type": "string" + }, "base_url": { "type": "string" }, "embedding_parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.EmbeddingParameters" + "$ref": "#/definitions/types.EmbeddingParameters" }, "extra_config": { "description": "Provider-specific configuration", @@ -10540,7 +11921,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ModelSource": { + "types.ModelSource": { "type": "string", "enum": [ "local", @@ -10558,10 +11939,12 @@ const docTemplate = `{ "jina", "openrouter", "nvidia", - "novita" + "novita", + "azure_openai" ], "x-enum-comments": { "ModelSourceAliyun": "Aliyun DashScope model", + "ModelSourceAzureOpenAI": "Azure OpenAI model", "ModelSourceDeepseek": "Deepseek model", "ModelSourceGemini": "Gemini model", "ModelSourceHunyuan": "Hunyuan model", @@ -10594,7 +11977,8 @@ const docTemplate = `{ "Jina AI model", "OpenRouter model", "NVIDIA model", - "Novita AI model" + "Novita AI model", + "Azure OpenAI model" ], "x-enum-varnames": [ "ModelSourceLocal", @@ -10612,18 +11996,21 @@ const docTemplate = `{ "ModelSourceJina", "ModelSourceOpenRouter", "ModelSourceNvidia", - "ModelSourceNovita" + "ModelSourceNovita", + "ModelSourceAzureOpenAI" ] }, - "github_com_Tencent_WeKnora_internal_types.ModelType": { + "types.ModelType": { "type": "string", "enum": [ "Embedding", "Rerank", "KnowledgeQA", - "VLLM" + "VLLM", + "ASR" ], "x-enum-comments": { + "ModelTypeASR": "ASR (Automatic Speech Recognition) model", "ModelTypeEmbedding": "Embedding model", "ModelTypeKnowledgeQA": "KnowledgeQA model", "ModelTypeRerank": "Rerank model", @@ -10633,16 +12020,18 @@ const docTemplate = `{ "Embedding model", "Rerank model", "KnowledgeQA model", - "VLLM model" + "VLLM model", + "ASR (Automatic Speech Recognition) model" ], "x-enum-varnames": [ "ModelTypeEmbedding", "ModelTypeRerank", "ModelTypeKnowledgeQA", - "ModelTypeVLLM" + "ModelTypeVLLM", + "ModelTypeASR" ] }, - "github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse": { + "types.OIDCAuthURLResponse": { "type": "object", "properties": { "authorization_url": { @@ -10659,7 +12048,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse": { + "types.OIDCConfigResponse": { "type": "object", "properties": { "enabled": { @@ -10673,7 +12062,39 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.OrgMemberRole": { + "types.OSSEngineConfig": { + "type": "object", + "properties": { + "access_key": { + "type": "string" + }, + "bucket_name": { + "type": "string" + }, + "endpoint": { + "type": "string" + }, + "path_prefix": { + "type": "string" + }, + "region": { + "type": "string" + }, + "secret_key": { + "type": "string" + }, + "temp_bucket_name": { + "type": "string" + }, + "temp_region": { + "type": "string" + }, + "use_temp_bucket": { + "type": "boolean" + } + } + }, + "types.OrgMemberRole": { "type": "string", "enum": [ "admin", @@ -10686,7 +12107,7 @@ const docTemplate = `{ "OrgRoleViewer" ] }, - "github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse": { + "types.OrganizationMemberResponse": { "type": "object", "properties": { "avatar": { @@ -10715,7 +12136,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.OrganizationResponse": { + "types.OrganizationResponse": { "type": "object", "properties": { "agent_share_count": { @@ -10785,13 +12206,9 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ParserEngineConfig": { + "types.ParserEngineConfig": { "type": "object", "properties": { - "docreader_addr": { - "description": "文档解析服务地址", - "type": "string" - }, "mineru_api_key": { "description": "MinerU 云 API Key", "type": "string" @@ -10834,7 +12251,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ParserEngineRule": { + "types.ParserEngineRule": { "type": "object", "properties": { "engine": { @@ -10848,7 +12265,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig": { + "types.QuestionGenerationConfig": { "type": "object", "properties": { "enabled": { @@ -10860,7 +12277,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.RegisterRequest": { + "types.RegisterRequest": { "type": "object", "required": [ "email", @@ -10882,7 +12299,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.RegisterResponse": { + "types.RegisterResponse": { "type": "object", "properties": { "message": { @@ -10892,14 +12309,14 @@ const docTemplate = `{ "type": "boolean" }, "tenant": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" }, "user": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.User" + "$ref": "#/definitions/types.User" } } }, - "github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest": { + "types.RequestRoleUpgradeRequest": { "type": "object", "required": [ "requested_role" @@ -10914,13 +12331,13 @@ const docTemplate = `{ "description": "The role user wants to upgrade to", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.Resource": { + "types.Resource": { "type": "object", "properties": { "description": { @@ -10931,6 +12348,10 @@ const docTemplate = `{ "description": "Unique identifier in the external system", "type": "string" }, + "has_children": { + "description": "Whether this resource has children that can be expanded", + "type": "boolean" + }, "metadata": { "description": "Additional metadata", "type": "object", @@ -10958,7 +12379,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse": { + "types.ResourceCountsByOrgResponse": { "type": "object", "properties": { "agents": { @@ -10985,7 +12406,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.RetrievalConfig": { + "types.RetrievalConfig": { "type": "object", "properties": { "embedding_top_k": { @@ -11014,14 +12435,14 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams": { + "types.RetrieverEngineParams": { "type": "object", "properties": { "retriever_engine_type": { "description": "Retriever engine type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineType" + "$ref": "#/definitions/types.RetrieverEngineType" } ] }, @@ -11029,13 +12450,13 @@ const docTemplate = `{ "description": "Retriever type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverType" + "$ref": "#/definitions/types.RetrieverType" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngineType": { + "types.RetrieverEngineType": { "type": "string", "enum": [ "postgres", @@ -11058,18 +12479,18 @@ const docTemplate = `{ "SQLiteRetrieverEngineType" ] }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngines": { + "types.RetrieverEngines": { "type": "object", "properties": { "engines": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams" + "$ref": "#/definitions/types.RetrieverEngineParams" } } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverType": { + "types.RetrieverType": { "type": "string", "enum": [ "keywords", @@ -11092,7 +12513,7 @@ const docTemplate = `{ "WebSearchRetrieverType" ] }, - "github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest": { + "types.ReviewJoinRequestRequest": { "type": "object", "properties": { "approved": { @@ -11106,13 +12527,13 @@ const docTemplate = `{ "description": "Optional: role to assign when approving; overrides applicant's requested role", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.S3EngineConfig": { + "types.S3EngineConfig": { "type": "object", "properties": { "access_key": { @@ -11135,7 +12556,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.SearchParams": { + "types.SearchParams": { "type": "object", "properties": { "disable_keywords_match": { @@ -11191,7 +12612,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.SearchResult": { + "types.SearchResult": { "type": "object", "properties": { "chunk_index": { @@ -11257,7 +12678,7 @@ const docTemplate = `{ "description": "Match type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MatchType" + "$ref": "#/definitions/types.MatchType" } ] }, @@ -11297,7 +12718,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.Session": { + "types.Session": { "type": "object", "properties": { "created_at": { @@ -11327,7 +12748,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest": { + "types.ShareKnowledgeBaseRequest": { "type": "object", "required": [ "organization_id", @@ -11338,11 +12759,11 @@ const docTemplate = `{ "type": "string" }, "permission": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.StorageConfig": { + "types.StorageConfig": { "type": "object", "properties": { "app_id": { @@ -11368,40 +12789,43 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.StorageEngineConfig": { + "types.StorageEngineConfig": { "type": "object", "properties": { "cos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig" + "$ref": "#/definitions/types.COSEngineConfig" }, "default_provider": { - "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\"", + "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", "type": "string" }, "local": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LocalEngineConfig" + "$ref": "#/definitions/types.LocalEngineConfig" }, "minio": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig" + "$ref": "#/definitions/types.MinIOEngineConfig" + }, + "oss": { + "$ref": "#/definitions/types.OSSEngineConfig" }, "s3": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig" + "$ref": "#/definitions/types.S3EngineConfig" }, "tos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig" + "$ref": "#/definitions/types.TOSEngineConfig" } } }, - "github_com_Tencent_WeKnora_internal_types.StorageProviderConfig": { + "types.StorageProviderConfig": { "type": "object", "properties": { "provider": { - "description": "\"local\", \"minio\", \"cos\", \"tos\"", + "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest": { + "types.SubmitJoinRequestRequest": { "type": "object", "required": [ "invite_code" @@ -11420,13 +12844,13 @@ const docTemplate = `{ "description": "Optional: role the applicant requests (admin/editor/viewer); default viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.SyncLog": { + "types.SyncLog": { "type": "object", "properties": { "created_at": { @@ -11498,7 +12922,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.TOSEngineConfig": { + "types.TOSEngineConfig": { "type": "object", "properties": { "access_key": { @@ -11521,14 +12945,14 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.Tenant": { + "types.Tenant": { "type": "object", "properties": { "agent_config": { "description": "Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.\nThis field is kept for backward compatibility and will be removed in future versions.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AgentConfig" + "$ref": "#/definitions/types.AgentConfig" } ] }, @@ -11544,7 +12968,7 @@ const docTemplate = `{ "description": "Chat history config: knowledge base configuration for indexing and searching chat messages via vector search", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig" + "$ref": "#/definitions/types.ChatHistoryConfig" } ] }, @@ -11552,7 +12976,7 @@ const docTemplate = `{ "description": "Global Context configuration for this tenant (default for all sessions)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ContextConfig" + "$ref": "#/definitions/types.ContextConfig" } ] }, @@ -11560,7 +12984,7 @@ const docTemplate = `{ "description": "Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.\nThis field is kept for backward compatibility and will be removed in future versions.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ConversationConfig" + "$ref": "#/definitions/types.ConversationConfig" } ] }, @@ -11568,6 +12992,14 @@ const docTemplate = `{ "description": "Creation time", "type": "string" }, + "credentials": { + "description": "Credentials config: third-party provider credentials (e.g. WeKnoraCloud AppID/AppSecret)", + "allOf": [ + { + "$ref": "#/definitions/types.CredentialsConfig" + } + ] + }, "deleted_at": { "description": "Deletion time", "allOf": [ @@ -11592,7 +13024,7 @@ const docTemplate = `{ "description": "Parser engine config overrides (MinerU endpoint, API key, etc.). Used when parsing documents; overrides env.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineConfig" + "$ref": "#/definitions/types.ParserEngineConfig" } ] }, @@ -11600,7 +13032,7 @@ const docTemplate = `{ "description": "Retrieval config: global search/retrieval parameters shared by knowledge search and message search", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrievalConfig" + "$ref": "#/definitions/types.RetrievalConfig" } ] }, @@ -11608,7 +13040,7 @@ const docTemplate = `{ "description": "Retriever engines", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngines" + "$ref": "#/definitions/types.RetrieverEngines" } ] }, @@ -11620,7 +13052,7 @@ const docTemplate = `{ "description": "Storage engine config: parameters for Local, MinIO, COS. Used for document/file storage and docreader.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageEngineConfig" + "$ref": "#/definitions/types.StorageEngineConfig" } ] }, @@ -11640,13 +13072,13 @@ const docTemplate = `{ "description": "Global WebSearch configuration for this tenant", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WebSearchConfig" + "$ref": "#/definitions/types.WebSearchConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.ToolCall": { + "types.ToolCall": { "type": "object", "properties": { "args": { @@ -11674,13 +13106,13 @@ const docTemplate = `{ "description": "Execution result (contains Output)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolResult" + "$ref": "#/definitions/types.ToolResult" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.ToolResult": { + "types.ToolResult": { "type": "object", "properties": { "data": { @@ -11709,18 +13141,18 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest": { + "types.UpdateMemberRoleRequest": { "type": "object", "required": [ "role" ], "properties": { "role": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest": { + "types.UpdateOrganizationRequest": { "type": "object", "properties": { "avatar": { @@ -11754,18 +13186,18 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest": { + "types.UpdateSharePermissionRequest": { "type": "object", "required": [ "permission" ], "properties": { "permission": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.User": { + "types.User": { "type": "object", "properties": { "avatar": { @@ -11804,7 +13236,7 @@ const docTemplate = `{ "description": "Association relationship, not stored in the database", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } ] }, @@ -11822,7 +13254,7 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.VLMConfig": { + "types.VLMConfig": { "type": "object", "properties": { "api_key": { @@ -11849,11 +13281,22 @@ const docTemplate = `{ } } }, - "github_com_Tencent_WeKnora_internal_types.WebSearchConfig": { + "types.WeKnoraCloudCredentials": { + "type": "object", + "properties": { + "app_id": { + "type": "string" + }, + "app_secret": { + "type": "string" + } + } + }, + "types.WebSearchConfig": { "type": "object", "properties": { "api_key": { - "description": "API密钥(如果需要)", + "description": "Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.", "type": "string" }, "blacklist": { @@ -11888,7 +13331,7 @@ const docTemplate = `{ "type": "integer" }, "provider": { - "description": "搜索引擎提供商ID", + "description": "Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.", "type": "string" }, "rerank_model_id": { @@ -11896,731 +13339,6 @@ const docTemplate = `{ "type": "string" } } - }, - "gorm.DeletedAt": { - "type": "object", - "properties": { - "time": { - "type": "string" - }, - "valid": { - "description": "Valid is true if Time is not NULL", - "type": "boolean" - } - } - }, - "internal_handler.CopyKnowledgeBaseRequest": { - "type": "object", - "required": [ - "source_id" - ], - "properties": { - "source_id": { - "type": "string" - }, - "target_id": { - "type": "string" - }, - "task_id": { - "type": "string" - } - } - }, - "internal_handler.CreateAgentRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "avatar": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.CreateModelRequest": { - "type": "object", - "required": [ - "name", - "parameters", - "source", - "type" - ], - "properties": { - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters" - }, - "source": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource" - }, - "type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType" - } - } - }, - "internal_handler.DeleteTagRequest": { - "type": "object", - "properties": { - "exclude_ids": { - "description": "Chunk seq_ids to exclude from deletion", - "type": "array", - "items": { - "type": "integer" - } - } - } - }, - "internal_handler.EvaluationRequest": { - "type": "object", - "properties": { - "chat_id": { - "description": "ID of chat model to use", - "type": "string" - }, - "dataset_id": { - "description": "ID of dataset to evaluate", - "type": "string" - }, - "knowledge_base_id": { - "description": "ID of knowledge base to use", - "type": "string" - }, - "rerank_id": { - "description": "ID of rerank model to use", - "type": "string" - } - } - }, - "internal_handler.FabriTextRequest": { - "type": "object", - "required": [ - "model_id" - ], - "properties": { - "model_id": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "internal_handler.GetStorageEngineStatusResponse": { - "type": "object", - "properties": { - "engines": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler.StorageEngineStatusItem" - } - }, - "minio_env_available": { - "type": "boolean" - } - } - }, - "internal_handler.GetSystemInfoResponse": { - "type": "object", - "properties": { - "build_time": { - "type": "string" - }, - "commit_id": { - "type": "string" - }, - "db_version": { - "type": "string" - }, - "edition": { - "type": "string" - }, - "go_version": { - "type": "string" - }, - "graph_database_engine": { - "type": "string" - }, - "keyword_index_engine": { - "type": "string" - }, - "minio_enabled": { - "type": "boolean" - }, - "vector_store_engine": { - "type": "string" - }, - "version": { - "type": "string" - } - } - }, - "internal_handler.KBModelConfigRequest": { - "type": "object", - "required": [ - "embeddingModelId", - "llmModelId" - ], - "properties": { - "documentSplitting": { - "description": "文档分块配置", - "type": "object", - "properties": { - "childChunkSize": { - "type": "integer" - }, - "chunkOverlap": { - "type": "integer" - }, - "chunkSize": { - "type": "integer" - }, - "enableParentChild": { - "type": "boolean" - }, - "parentChunkSize": { - "type": "integer" - }, - "parserEngineRules": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule" - } - }, - "separators": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "embeddingModelId": { - "type": "string" - }, - "llmModelId": { - "type": "string" - }, - "multimodal": { - "description": "多模态配置(仅模型相关;存储引擎在 storageProvider 中配置)", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - } - } - }, - "nodeExtract": { - "description": "知识图谱配置", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - }, - "nodes": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode" - } - }, - "relations": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation" - } - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "text": { - "type": "string" - } - } - }, - "questionGeneration": { - "description": "问题生成配置", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - }, - "questionCount": { - "type": "integer" - } - } - }, - "storageProvider": { - "description": "存储引擎选择(\"local\" | \"minio\" | \"cos\"),影响文档上传与文档内图片存储,参数从全局设置读取", - "type": "string" - }, - "vlm_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" - } - } - }, - "internal_handler.ListMinioBucketsResponse": { - "type": "object", - "properties": { - "buckets": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler.MinioBucketInfo" - } - } - } - }, - "internal_handler.MinioBucketInfo": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "name": { - "type": "string" - }, - "policy": { - "description": "\"public\", \"private\", \"custom\"", - "type": "string" - } - } - }, - "internal_handler.RemoteModelCheckRequest": { - "type": "object", - "required": [ - "baseUrl", - "modelName" - ], - "properties": { - "apiKey": { - "type": "string" - }, - "baseUrl": { - "type": "string" - }, - "modelName": { - "type": "string" - } - } - }, - "internal_handler.SearchMessagesRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "limit": { - "description": "Maximum number of results to return (default: 20)", - "type": "integer" - }, - "mode": { - "description": "Search mode: \"keyword\", \"vector\", \"hybrid\" (default: \"hybrid\")", - "type": "string" - }, - "query": { - "description": "Query text for search", - "type": "string" - }, - "session_ids": { - "description": "Filter by specific session IDs (optional)", - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "internal_handler.StorageCheckRequest": { - "type": "object", - "properties": { - "cos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig" - }, - "minio": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig" - }, - "provider": { - "description": "\"minio\", \"cos\", \"tos\", or \"s3\"", - "type": "string" - }, - "s3": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig" - }, - "tos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig" - } - } - }, - "internal_handler.StorageCheckResponse": { - "type": "object", - "properties": { - "bucket_created": { - "type": "boolean" - }, - "message": { - "type": "string" - }, - "ok": { - "type": "boolean" - } - } - }, - "internal_handler.StorageEngineStatusItem": { - "type": "object", - "properties": { - "available": { - "description": "whether the engine can be used", - "type": "boolean" - }, - "description": { - "description": "short description for UI", - "type": "string" - }, - "name": { - "description": "\"local\", \"minio\", \"cos\", \"tos\"", - "type": "string" - } - } - }, - "internal_handler.TextRelationExtractionRequest": { - "type": "object", - "required": [ - "model_id", - "tags", - "text" - ], - "properties": { - "model_id": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "text": { - "type": "string" - } - } - }, - "internal_handler.UpdateAgentRequest": { - "type": "object", - "properties": { - "avatar": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.UpdateChunkRequest": { - "type": "object", - "properties": { - "chunk_index": { - "type": "integer" - }, - "content": { - "type": "string" - }, - "embedding": { - "type": "array", - "items": { - "type": "number" - } - }, - "end_at": { - "type": "integer" - }, - "image_info": { - "type": "string" - }, - "is_enabled": { - "type": "boolean" - }, - "start_at": { - "type": "integer" - } - } - }, - "internal_handler.UpdateKnowledgeBaseRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.UpdateModelRequest": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters" - }, - "source": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource" - }, - "type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType" - } - } - }, - "internal_handler.addSimilarQuestionsRequest": { - "type": "object", - "required": [ - "similar_questions" - ], - "properties": { - "similar_questions": { - "type": "array", - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "internal_handler.updateLastFAQImportResultDisplayStatusRequest": { - "type": "object", - "required": [ - "display_status" - ], - "properties": { - "display_status": { - "type": "string", - "enum": [ - "open", - "close" - ] - } - } - }, - "internal_handler_session.CreateKnowledgeQARequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "agent_enabled": { - "description": "Whether agent mode is enabled for this request", - "type": "boolean" - }, - "agent_id": { - "description": "Selected custom agent ID (backend resolves shared agent and its tenant from share relation)", - "type": "string" - }, - "channel": { - "description": "Source channel: \"web\", \"api\", \"im\", etc.", - "type": "string" - }, - "disable_title": { - "description": "Whether to disable auto title generation", - "type": "boolean" - }, - "enable_memory": { - "description": "Whether memory feature is enabled for this request", - "type": "boolean" - }, - "images": { - "description": "Attached images for multimodal chat", - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.ImageAttachment" - } - }, - "knowledge_base_ids": { - "description": "Selected knowledge base ID for this request", - "type": "array", - "items": { - "type": "string" - } - }, - "knowledge_ids": { - "description": "Selected knowledge ID for this request", - "type": "array", - "items": { - "type": "string" - } - }, - "mentioned_items": { - "description": "@mentioned knowledge bases and files", - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.MentionedItemRequest" - } - }, - "query": { - "description": "Query text for knowledge base search", - "type": "string" - }, - "summary_model_id": { - "description": "Optional summary model ID for this request (overrides session default)", - "type": "string" - }, - "web_search_enabled": { - "description": "Whether web search is enabled for this request", - "type": "boolean" - } - } - }, - "internal_handler_session.CreateSessionRequest": { - "type": "object", - "properties": { - "description": { - "description": "Description for the session (optional)", - "type": "string" - }, - "title": { - "description": "Title for the session (optional)", - "type": "string" - } - } - }, - "internal_handler_session.GenerateTitleRequest": { - "type": "object", - "required": [ - "messages" - ], - "properties": { - "messages": { - "description": "Messages to use as context for title generation", - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Message" - } - } - } - }, - "internal_handler_session.ImageAttachment": { - "type": "object", - "properties": { - "caption": { - "description": "VLM analysis result (context-aware, single call)", - "type": "string" - }, - "data": { - "description": "base64 data URI from frontend (data:image/png;base64,...)", - "type": "string" - }, - "url": { - "description": "serving URL after saving to storage", - "type": "string" - } - } - }, - "internal_handler_session.MentionedItemRequest": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "kb_type": { - "description": "\"document\" or \"faq\" (only for kb type)", - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "description": "\"kb\" for knowledge base, \"file\" for file", - "type": "string" - } - } - }, - "internal_handler_session.SearchKnowledgeRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "knowledge_base_id": { - "description": "Single knowledge base ID (for backward compatibility)", - "type": "string" - }, - "knowledge_base_ids": { - "description": "IDs of knowledge bases to search (multi-KB support)", - "type": "array", - "items": { - "type": "string" - } - }, - "knowledge_ids": { - "description": "IDs of specific knowledge (files) to search", - "type": "array", - "items": { - "type": "string" - } - }, - "query": { - "description": "Query text to search for", - "type": "string" - } - } - }, - "internal_handler_session.StopSessionRequest": { - "type": "object", - "required": [ - "message_id" - ], - "properties": { - "message_id": { - "type": "string" - } - } - }, - "internal_handler_session.batchDeleteRequest": { - "type": "object", - "properties": { - "delete_all": { - "type": "boolean" - }, - "ids": { - "type": "array", - "items": { - "type": "string" - } - } - } } }, "securityDefinitions": { diff --git a/docs/swagger.json b/docs/swagger.json index 9891d92d..13adbdb1 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -44,7 +44,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -76,7 +76,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CreateAgentRequest" + "$ref": "#/definitions/handler.CreateAgentRequest" } } ], @@ -91,7 +91,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -170,13 +170,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -215,7 +215,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateAgentRequest" + "$ref": "#/definitions/handler.UpdateAgentRequest" } } ], @@ -230,13 +230,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "无法修改内置智能体", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -281,19 +281,19 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "无法删除内置智能体", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -340,13 +340,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -411,13 +411,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "智能体不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -448,7 +448,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } }, @@ -482,7 +482,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } ], @@ -490,7 +490,7 @@ "201": { "description": "Created", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "400": { @@ -528,7 +528,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } }, "404": { @@ -559,7 +559,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata" + "$ref": "#/definitions/datasource.ConnectorMetadata" } } } @@ -635,7 +635,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "404": { @@ -675,7 +675,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } } ], @@ -683,7 +683,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource" + "$ref": "#/definitions/types.DataSource" } }, "400": { @@ -765,7 +765,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } } }, @@ -844,7 +844,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Resource" + "$ref": "#/definitions/types.Resource" } } }, @@ -918,7 +918,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } }, "400": { @@ -971,6 +971,35 @@ } } }, + "/auth/auto-setup": { + "post": { + "description": "Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "认证" + ], + "summary": "自动初始化(Lite 桌面版)", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/types.LoginResponse" + } + }, + "403": { + "description": "非 Lite 版本", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, "/auth/change-password": { "post": { "security": [ @@ -1019,7 +1048,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1045,7 +1074,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LoginRequest" + "$ref": "#/definitions/types.LoginRequest" } } ], @@ -1053,13 +1082,13 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LoginResponse" + "$ref": "#/definitions/types.LoginResponse" } }, "401": { "description": "认证失败", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1094,7 +1123,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1129,7 +1158,7 @@ "401": { "description": "未授权", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1192,7 +1221,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse" + "$ref": "#/definitions/types.OIDCConfigResponse" } } } @@ -1224,19 +1253,19 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse" + "$ref": "#/definitions/types.OIDCAuthURLResponse" } }, "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "OIDC未启用", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1282,7 +1311,7 @@ "401": { "description": "令牌无效", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1308,7 +1337,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterRequest" + "$ref": "#/definitions/types.RegisterRequest" } } ], @@ -1316,19 +1345,19 @@ "201": { "description": "Created", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterResponse" + "$ref": "#/definitions/types.RegisterResponse" } }, "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "注册功能已禁用", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1363,7 +1392,7 @@ "401": { "description": "令牌无效", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1410,13 +1439,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1477,13 +1506,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1544,7 +1573,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1589,7 +1618,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1637,7 +1666,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateChunkRequest" + "$ref": "#/definitions/handler.UpdateChunkRequest" } } ], @@ -1652,13 +1681,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1710,13 +1739,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "分块不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1763,7 +1792,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1795,7 +1824,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.EvaluationRequest" + "$ref": "#/definitions/handler.EvaluationRequest" } } ], @@ -1810,7 +1839,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1857,7 +1886,7 @@ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1891,7 +1920,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.TextRelationExtractionRequest" + "$ref": "#/definitions/handler.TextRelationExtractionRequest" } } ], @@ -1906,7 +1935,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -1964,7 +1993,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.FabriTextRequest" + "$ref": "#/definitions/handler.FabriTextRequest" } } ], @@ -1979,7 +2008,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2035,7 +2064,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2082,7 +2111,7 @@ "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2121,7 +2150,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.KBModelConfigRequest" + "$ref": "#/definitions/handler.KBModelConfigRequest" } } ], @@ -2136,13 +2165,62 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, + "/initialization/models/asr/check": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "检查ASR(语音识别)模型连接是否正常,通过发送一段静默音频测试 /v1/audio/transcriptions 端点", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "初始化" + ], + "summary": "检查ASR模型", + "parameters": [ + { + "description": "ASR检查请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "检查结果", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/errors.AppError" } } } @@ -2191,7 +2269,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2225,7 +2303,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.RemoteModelCheckRequest" + "$ref": "#/definitions/handler.RemoteModelCheckRequest" } } ], @@ -2240,7 +2318,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2289,7 +2367,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2369,7 +2447,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2448,7 +2526,7 @@ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2486,7 +2564,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2543,7 +2621,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2597,7 +2675,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2667,7 +2745,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2699,7 +2777,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBase" + "$ref": "#/definitions/types.KnowledgeBase" } } ], @@ -2714,7 +2792,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2748,7 +2826,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CopyKnowledgeBaseRequest" + "$ref": "#/definitions/handler.CopyKnowledgeBaseRequest" } } ], @@ -2763,7 +2841,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2810,7 +2888,7 @@ "404": { "description": "任务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2863,13 +2941,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2908,7 +2986,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateKnowledgeBaseRequest" + "$ref": "#/definitions/handler.UpdateKnowledgeBaseRequest" } } ], @@ -2923,7 +3001,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -2968,7 +3046,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3051,7 +3129,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3090,7 +3168,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload" + "$ref": "#/definitions/types.FAQBatchUpsertPayload" } } ], @@ -3105,7 +3183,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3167,7 +3245,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3213,7 +3291,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3254,7 +3332,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsBatchUpdate" } } ], @@ -3269,7 +3347,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3325,7 +3403,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3379,13 +3457,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "条目不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3431,7 +3509,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } } ], @@ -3446,7 +3524,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3494,7 +3572,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.addSimilarQuestionsRequest" + "$ref": "#/definitions/handler.addSimilarQuestionsRequest" } } ], @@ -3509,13 +3587,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "条目不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3556,7 +3634,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } } ], @@ -3571,7 +3649,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3612,7 +3690,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.updateLastFAQImportResultDisplayStatusRequest" + "$ref": "#/definitions/handler.updateLastFAQImportResultDisplayStatusRequest" } } ], @@ -3627,13 +3705,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识库不存在或无导入记录", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3674,7 +3752,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQSearchRequest" + "$ref": "#/definitions/types.FAQSearchRequest" } } ], @@ -3689,7 +3767,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3730,7 +3808,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SearchParams" + "$ref": "#/definitions/types.SearchParams" } } ], @@ -3745,7 +3823,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3822,7 +3900,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3867,13 +3945,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -3945,7 +4023,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "409": { @@ -3993,7 +4071,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload" + "$ref": "#/definitions/types.ManualKnowledgePayload" } } ], @@ -4008,7 +4086,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4084,7 +4162,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "409": { @@ -4138,7 +4216,7 @@ "404": { "description": "知识库不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4172,7 +4250,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse" + "$ref": "#/definitions/types.ListSharesResponse" } } } @@ -4208,7 +4286,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest" + "$ref": "#/definitions/types.ShareKnowledgeBaseRequest" } } ], @@ -4268,7 +4346,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest" + "$ref": "#/definitions/types.UpdateSharePermissionRequest" } } ], @@ -4391,7 +4469,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4456,7 +4534,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4519,7 +4597,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4576,7 +4654,7 @@ "name": "body", "in": "body", "schema": { - "$ref": "#/definitions/internal_handler.DeleteTagRequest" + "$ref": "#/definitions/handler.DeleteTagRequest" } } ], @@ -4591,7 +4669,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4654,7 +4732,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4722,7 +4800,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4763,7 +4841,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload" + "$ref": "#/definitions/types.ManualKnowledgePayload" } } ], @@ -4778,7 +4856,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4848,7 +4926,7 @@ "400": { "description": "Invalid request", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4897,7 +4975,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4944,13 +5022,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "知识不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -4989,7 +5067,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Knowledge" + "$ref": "#/definitions/types.Knowledge" } } ], @@ -5004,7 +5082,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5049,7 +5127,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5095,7 +5173,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5144,7 +5222,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5191,13 +5269,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5235,7 +5313,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5267,7 +5345,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPService" + "$ref": "#/definitions/types.MCPService" } } ], @@ -5282,7 +5360,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5329,7 +5407,7 @@ "404": { "description": "服务不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5383,7 +5461,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5428,7 +5506,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5475,7 +5553,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5522,7 +5600,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5569,7 +5647,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5635,7 +5713,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.SearchMessagesRequest" + "$ref": "#/definitions/handler.SearchMessagesRequest" } } ], @@ -5650,7 +5728,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5710,7 +5788,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5764,7 +5842,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5802,7 +5880,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5834,7 +5912,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.CreateModelRequest" + "$ref": "#/definitions/handler.CreateModelRequest" } } ], @@ -5849,7 +5927,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5936,7 +6014,7 @@ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -5975,7 +6053,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.UpdateModelRequest" + "$ref": "#/definitions/handler.UpdateModelRequest" } } ], @@ -5990,7 +6068,7 @@ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -6035,7 +6113,7 @@ "404": { "description": "模型不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -6060,7 +6138,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse" + "$ref": "#/definitions/types.ListOrganizationsResponse" } } } @@ -6089,7 +6167,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest" + "$ref": "#/definitions/types.CreateOrganizationRequest" } } ], @@ -6135,7 +6213,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest" + "$ref": "#/definitions/types.JoinOrganizationRequest" } } ], @@ -6181,7 +6259,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest" + "$ref": "#/definitions/types.JoinByOrganizationIDRequest" } } ], @@ -6227,7 +6305,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest" + "$ref": "#/definitions/types.SubmitJoinRequestRequest" } } ], @@ -6401,7 +6479,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest" + "$ref": "#/definitions/types.UpdateOrganizationRequest" } } ], @@ -6490,7 +6568,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.InviteMemberRequest" + "$ref": "#/definitions/types.InviteMemberRequest" } } ], @@ -6638,7 +6716,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest" + "$ref": "#/definitions/types.ReviewJoinRequestRequest" } } ], @@ -6725,7 +6803,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListMembersResponse" + "$ref": "#/definitions/types.ListMembersResponse" } } } @@ -6770,7 +6848,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest" + "$ref": "#/definitions/types.UpdateMemberRoleRequest" } } ], @@ -6866,7 +6944,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest" + "$ref": "#/definitions/types.RequestRoleUpgradeRequest" } } ], @@ -7040,7 +7118,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse" + "$ref": "#/definitions/types.ListSharesResponse" } } } @@ -7092,7 +7170,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7124,7 +7202,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateSessionRequest" + "$ref": "#/definitions/handler_session.CreateSessionRequest" } } ], @@ -7139,7 +7217,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7173,7 +7251,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.batchDeleteRequest" + "$ref": "#/definitions/handler_session.batchDeleteRequest" } } ], @@ -7188,7 +7266,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7222,7 +7300,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.SearchKnowledgeRequest" + "$ref": "#/definitions/handler_session.SearchKnowledgeRequest" } } ], @@ -7237,7 +7315,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7284,7 +7362,7 @@ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7323,7 +7401,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Session" + "$ref": "#/definitions/types.Session" } } ], @@ -7338,7 +7416,7 @@ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7383,7 +7461,7 @@ "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7430,13 +7508,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "会话不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7477,7 +7555,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateKnowledgeQARequest" + "$ref": "#/definitions/handler_session.CreateKnowledgeQARequest" } } ], @@ -7492,7 +7570,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7546,7 +7624,7 @@ "404": { "description": "会话或消息不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7587,7 +7665,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.CreateKnowledgeQARequest" + "$ref": "#/definitions/handler_session.CreateKnowledgeQARequest" } } ], @@ -7602,7 +7680,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7643,7 +7721,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.StopSessionRequest" + "$ref": "#/definitions/handler_session.StopSessionRequest" } } ], @@ -7658,7 +7736,7 @@ "404": { "description": "会话或消息不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7699,7 +7777,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler_session.GenerateTitleRequest" + "$ref": "#/definitions/handler_session.GenerateTitleRequest" } } ], @@ -7714,7 +7792,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7778,7 +7856,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -7831,44 +7909,7 @@ "200": { "description": "系统信息", "schema": { - "$ref": "#/definitions/internal_handler.GetSystemInfoResponse" - } - } - } - } - }, - "/system/minio/buckets": { - "get": { - "description": "获取所有 MinIO 存储桶及其访问权限", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "系统" - ], - "summary": "列出 MinIO 存储桶", - "responses": { - "200": { - "description": "存储桶列表", - "schema": { - "$ref": "#/definitions/internal_handler.ListMinioBucketsResponse" - } - }, - "400": { - "description": "MinIO 未启用", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "500": { - "description": "服务器错误", - "schema": { - "type": "object", - "additionalProperties": true + "$ref": "#/definitions/handler.GetSystemInfoResponse" } } } @@ -7944,7 +7985,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/internal_handler.StorageCheckRequest" + "$ref": "#/definitions/handler.StorageCheckRequest" } } ], @@ -7952,7 +7993,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/internal_handler.StorageCheckResponse" + "$ref": "#/definitions/handler.StorageCheckResponse" } } } @@ -7972,7 +8013,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/internal_handler.GetStorageEngineStatusResponse" + "$ref": "#/definitions/handler.GetStorageEngineStatusResponse" } } } @@ -8007,7 +8048,7 @@ "500": { "description": "服务器错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8036,7 +8077,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } } ], @@ -8051,7 +8092,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8086,7 +8127,7 @@ "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8124,7 +8165,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8162,7 +8203,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8200,7 +8241,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8238,7 +8279,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8285,7 +8326,7 @@ "400": { "description": "不支持的键", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8339,7 +8380,7 @@ "400": { "description": "不支持的键", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8405,7 +8446,7 @@ "403": { "description": "权限不足", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8452,13 +8493,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } }, "404": { "description": "租户不存在", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8494,7 +8535,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } } ], @@ -8509,7 +8550,7 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } @@ -8551,13 +8592,13 @@ "400": { "description": "请求参数错误", "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + "$ref": "#/definitions/errors.AppError" } } } } }, - "/web-search/providers": { + "/vector-stores": { "get": { "security": [ { @@ -8567,7 +8608,41 @@ "ApiKeyAuth": [] } ], - "description": "Returns the list of available web search providers from configuration", + "description": "List all vector stores for the current tenant, including environment-configured and user-created stores", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "List vector stores", + "responses": { + "200": { + "description": "List of vector stores (env + DB)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Create a new vector store configuration for the current tenant", "consumes": [ "application/json" ], @@ -8575,12 +8650,349 @@ "application/json" ], "tags": [ - "web-search" + "VectorStore" + ], + "summary": "Create vector store", + "parameters": [ + { + "description": "Vector store configuration", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.CreateStoreRequest" + } + } + ], + "responses": { + "201": { + "description": "Created vector store", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid request or validation error", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "409": { + "description": "Duplicate endpoint and index", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + } + } + } + }, + "/vector-stores/test": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Test connectivity using provided credentials without persisting. Returns detected server version.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Test vector store connection with raw credentials", + "parameters": [ + { + "description": "Engine type and connection config", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.TestStoreRequest" + } + } ], - "summary": "Get available web search providers", "responses": { "200": { - "description": "List of providers", + "description": "Connection test result (success, version)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid request", + "schema": { + "$ref": "#/definitions/errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/types": { + "get": { + "description": "Return supported engine types with connection and index field schemas for UI form generation", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "List vector store types", + "responses": { + "200": { + "description": "List of engine types with config schemas", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/{id}": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Retrieve a single vector store by ID. Supports both DB stores and env stores (__env_* IDs)", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Get vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Vector store details", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "put": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Update a vector store (name only). Engine type, connection config, and index config are immutable. Env stores cannot be modified.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Update vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Updated fields", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handler.UpdateStoreRequest" + } + } + ], + "responses": { + "200": { + "description": "Updated vector store", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Env store or validation error", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + }, + "delete": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Soft-delete a vector store. Env stores cannot be deleted.", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Delete vector store", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Deletion success", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Env store cannot be deleted", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/vector-stores/{id}/test": { + "post": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Test connectivity of an existing saved or env store. Returns detected server version. For DB stores, the version is automatically saved to connection_config.", + "produces": [ + "application/json" + ], + "tags": [ + "VectorStore" + ], + "summary": "Test vector store connection by ID", + "parameters": [ + { + "type": "string", + "description": "Vector store ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Connection test result (success, version)", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Vector store not found", "schema": { "type": "object", "additionalProperties": true @@ -8591,7 +9003,7 @@ } }, "definitions": { - "github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata": { + "datasource.ConnectorMetadata": { "type": "object", "properties": { "auth_type": { @@ -8623,11 +9035,11 @@ } } }, - "github_com_Tencent_WeKnora_internal_errors.AppError": { + "errors.AppError": { "type": "object", "properties": { "code": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.ErrorCode" + "$ref": "#/definitions/errors.ErrorCode" }, "details": {}, "message": { @@ -8635,7 +9047,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_errors.ErrorCode": { + "errors.ErrorCode": { "type": "integer", "enum": [ 1000, @@ -8682,7 +9094,814 @@ "ErrAgentInvalidTemperature" ] }, - "github_com_Tencent_WeKnora_internal_types.AgentConfig": { + "github_com_Tencent_WeKnora_internal_errors.AppError": { + "type": "object", + "properties": { + "code": { + "$ref": "#/definitions/errors.ErrorCode" + }, + "details": {}, + "message": { + "type": "string" + } + } + }, + "gorm.DeletedAt": { + "type": "object", + "properties": { + "time": { + "type": "string" + }, + "valid": { + "description": "Valid is true if Time is not NULL", + "type": "boolean" + } + } + }, + "handler.CopyKnowledgeBaseRequest": { + "type": "object", + "required": [ + "source_id" + ], + "properties": { + "source_id": { + "type": "string" + }, + "target_id": { + "type": "string" + }, + "task_id": { + "type": "string" + } + } + }, + "handler.CreateAgentRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "avatar": { + "type": "string" + }, + "config": { + "$ref": "#/definitions/types.CustomAgentConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.CreateModelRequest": { + "type": "object", + "required": [ + "name", + "parameters", + "source", + "type" + ], + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "parameters": { + "$ref": "#/definitions/types.ModelParameters" + }, + "source": { + "$ref": "#/definitions/types.ModelSource" + }, + "type": { + "$ref": "#/definitions/types.ModelType" + } + } + }, + "handler.CreateStoreRequest": { + "type": "object", + "required": [ + "connection_config", + "engine_type", + "name" + ], + "properties": { + "connection_config": { + "$ref": "#/definitions/types.ConnectionConfig" + }, + "engine_type": { + "$ref": "#/definitions/types.RetrieverEngineType" + }, + "index_config": { + "$ref": "#/definitions/types.IndexConfig" + }, + "name": { + "type": "string" + } + } + }, + "handler.DeleteTagRequest": { + "type": "object", + "properties": { + "exclude_ids": { + "description": "Chunk seq_ids to exclude from deletion", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "handler.EvaluationRequest": { + "type": "object", + "properties": { + "chat_id": { + "description": "ID of chat model to use", + "type": "string" + }, + "dataset_id": { + "description": "ID of dataset to evaluate", + "type": "string" + }, + "knowledge_base_id": { + "description": "ID of knowledge base to use", + "type": "string" + }, + "rerank_id": { + "description": "ID of rerank model to use", + "type": "string" + } + } + }, + "handler.FabriTextRequest": { + "type": "object", + "required": [ + "model_id" + ], + "properties": { + "model_id": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "handler.GetStorageEngineStatusResponse": { + "type": "object", + "properties": { + "engines": { + "type": "array", + "items": { + "$ref": "#/definitions/handler.StorageEngineStatusItem" + } + }, + "minio_env_available": { + "type": "boolean" + } + } + }, + "handler.GetSystemInfoResponse": { + "type": "object", + "properties": { + "build_time": { + "type": "string" + }, + "commit_id": { + "type": "string" + }, + "db_version": { + "type": "string" + }, + "edition": { + "type": "string" + }, + "go_version": { + "type": "string" + }, + "graph_database_engine": { + "type": "string" + }, + "keyword_index_engine": { + "type": "string" + }, + "minio_enabled": { + "type": "boolean" + }, + "vector_store_engine": { + "type": "string" + }, + "version": { + "type": "string" + } + } + }, + "handler.KBModelConfigRequest": { + "type": "object", + "required": [ + "embeddingModelId", + "llmModelId" + ], + "properties": { + "asr_config": { + "$ref": "#/definitions/types.ASRConfig" + }, + "documentSplitting": { + "description": "文档分块配置", + "type": "object", + "properties": { + "childChunkSize": { + "type": "integer" + }, + "chunkOverlap": { + "type": "integer" + }, + "chunkSize": { + "type": "integer" + }, + "enableParentChild": { + "type": "boolean" + }, + "parentChunkSize": { + "type": "integer" + }, + "parserEngineRules": { + "type": "array", + "items": { + "$ref": "#/definitions/types.ParserEngineRule" + } + }, + "separators": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "embeddingModelId": { + "type": "string" + }, + "llmModelId": { + "type": "string" + }, + "multimodal": { + "description": "多模态配置(仅模型相关;存储引擎在 storageProvider 中配置)", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + } + } + }, + "nodeExtract": { + "description": "知识图谱配置", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "nodes": { + "type": "array", + "items": { + "$ref": "#/definitions/types.GraphNode" + } + }, + "relations": { + "type": "array", + "items": { + "$ref": "#/definitions/types.GraphRelation" + } + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + } + }, + "questionGeneration": { + "description": "问题生成配置", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "questionCount": { + "type": "integer" + } + } + }, + "storageProvider": { + "description": "存储引擎选择(\"local\" | \"minio\" | \"cos\"),影响文档上传与文档内图片存储,参数从全局设置读取", + "type": "string" + }, + "vlm_config": { + "$ref": "#/definitions/types.VLMConfig" + } + } + }, + "handler.RemoteModelCheckRequest": { + "type": "object", + "required": [ + "baseUrl", + "modelName" + ], + "properties": { + "apiKey": { + "type": "string" + }, + "baseUrl": { + "type": "string" + }, + "modelName": { + "type": "string" + }, + "provider": { + "type": "string" + } + } + }, + "handler.SearchMessagesRequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "limit": { + "description": "Maximum number of results to return (default: 20)", + "type": "integer" + }, + "mode": { + "description": "Search mode: \"keyword\", \"vector\", \"hybrid\" (default: \"hybrid\")", + "type": "string" + }, + "query": { + "description": "Query text for search", + "type": "string" + }, + "session_ids": { + "description": "Filter by specific session IDs (optional)", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "handler.StorageCheckRequest": { + "type": "object", + "properties": { + "cos": { + "$ref": "#/definitions/types.COSEngineConfig" + }, + "minio": { + "$ref": "#/definitions/types.MinIOEngineConfig" + }, + "oss": { + "$ref": "#/definitions/types.OSSEngineConfig" + }, + "provider": { + "description": "\"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", + "type": "string" + }, + "s3": { + "$ref": "#/definitions/types.S3EngineConfig" + }, + "tos": { + "$ref": "#/definitions/types.TOSEngineConfig" + } + } + }, + "handler.StorageCheckResponse": { + "type": "object", + "properties": { + "bucket_created": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "ok": { + "type": "boolean" + } + } + }, + "handler.StorageEngineStatusItem": { + "type": "object", + "properties": { + "available": { + "description": "whether the engine can be used", + "type": "boolean" + }, + "description": { + "description": "short description for UI", + "type": "string" + }, + "name": { + "description": "\"local\", \"minio\", \"cos\", \"tos\"", + "type": "string" + } + } + }, + "handler.TestStoreRequest": { + "type": "object", + "required": [ + "connection_config", + "engine_type" + ], + "properties": { + "connection_config": { + "$ref": "#/definitions/types.ConnectionConfig" + }, + "engine_type": { + "$ref": "#/definitions/types.RetrieverEngineType" + } + } + }, + "handler.TextRelationExtractionRequest": { + "type": "object", + "required": [ + "model_id", + "tags", + "text" + ], + "properties": { + "model_id": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + } + }, + "handler.UpdateAgentRequest": { + "type": "object", + "properties": { + "avatar": { + "type": "string" + }, + "config": { + "$ref": "#/definitions/types.CustomAgentConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.UpdateChunkRequest": { + "type": "object", + "properties": { + "chunk_index": { + "type": "integer" + }, + "content": { + "type": "string" + }, + "embedding": { + "type": "array", + "items": { + "type": "number" + } + }, + "end_at": { + "type": "integer" + }, + "image_info": { + "type": "string" + }, + "is_enabled": { + "type": "boolean" + }, + "start_at": { + "type": "integer" + } + } + }, + "handler.UpdateKnowledgeBaseRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "config": { + "$ref": "#/definitions/types.KnowledgeBaseConfig" + }, + "description": { + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "handler.UpdateModelRequest": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "name": { + "type": "string" + }, + "parameters": { + "$ref": "#/definitions/types.ModelParameters" + }, + "source": { + "$ref": "#/definitions/types.ModelSource" + }, + "type": { + "$ref": "#/definitions/types.ModelType" + } + } + }, + "handler.UpdateStoreRequest": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + } + } + }, + "handler.addSimilarQuestionsRequest": { + "type": "object", + "required": [ + "similar_questions" + ], + "properties": { + "similar_questions": { + "type": "array", + "minItems": 1, + "items": { + "type": "string" + } + } + } + }, + "handler.updateLastFAQImportResultDisplayStatusRequest": { + "type": "object", + "required": [ + "display_status" + ], + "properties": { + "display_status": { + "type": "string", + "enum": [ + "open", + "close" + ] + } + } + }, + "handler_session.AttachmentUpload": { + "type": "object", + "properties": { + "data": { + "description": "Base64-encoded file content", + "type": "string" + }, + "file_name": { + "description": "Original filename", + "type": "string" + }, + "file_size": { + "description": "File size in bytes", + "type": "integer" + } + } + }, + "handler_session.CreateKnowledgeQARequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "agent_enabled": { + "description": "Whether agent mode is enabled for this request", + "type": "boolean" + }, + "agent_id": { + "description": "Selected custom agent ID (backend resolves shared agent and its tenant from share relation)", + "type": "string" + }, + "attachment_uploads": { + "description": "Attached files (documents, audio, etc.)", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.AttachmentUpload" + } + }, + "channel": { + "description": "Source channel: \"web\", \"api\", \"im\", etc.", + "type": "string" + }, + "disable_title": { + "description": "Whether to disable auto title generation", + "type": "boolean" + }, + "enable_memory": { + "description": "Whether memory feature is enabled for this request", + "type": "boolean" + }, + "images": { + "description": "Attached images for multimodal chat", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.ImageAttachment" + } + }, + "knowledge_base_ids": { + "description": "Selected knowledge base ID for this request", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_ids": { + "description": "Selected knowledge ID for this request", + "type": "array", + "items": { + "type": "string" + } + }, + "mentioned_items": { + "description": "@mentioned knowledge bases and files", + "type": "array", + "items": { + "$ref": "#/definitions/handler_session.MentionedItemRequest" + } + }, + "query": { + "description": "Query text for knowledge base search", + "type": "string" + }, + "summary_model_id": { + "description": "Optional summary model ID for this request (overrides session default)", + "type": "string" + }, + "web_search_enabled": { + "description": "Whether web search is enabled for this request", + "type": "boolean" + } + } + }, + "handler_session.CreateSessionRequest": { + "type": "object", + "properties": { + "description": { + "description": "Description for the session (optional)", + "type": "string" + }, + "title": { + "description": "Title for the session (optional)", + "type": "string" + } + } + }, + "handler_session.GenerateTitleRequest": { + "type": "object", + "required": [ + "messages" + ], + "properties": { + "messages": { + "description": "Messages to use as context for title generation", + "type": "array", + "items": { + "$ref": "#/definitions/types.Message" + } + } + } + }, + "handler_session.ImageAttachment": { + "type": "object", + "properties": { + "caption": { + "description": "VLM analysis result (context-aware, single call)", + "type": "string" + }, + "data": { + "description": "base64 data URI from frontend (data:image/png;base64,...)", + "type": "string" + }, + "url": { + "description": "serving URL after saving to storage", + "type": "string" + } + } + }, + "handler_session.MentionedItemRequest": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kb_type": { + "description": "\"document\" or \"faq\" (only for kb type)", + "type": "string" + }, + "name": { + "type": "string" + }, + "type": { + "description": "\"kb\" for knowledge base, \"file\" for file", + "type": "string" + } + } + }, + "handler_session.SearchKnowledgeRequest": { + "type": "object", + "required": [ + "query" + ], + "properties": { + "knowledge_base_id": { + "description": "Single knowledge base ID (for backward compatibility)", + "type": "string" + }, + "knowledge_base_ids": { + "description": "IDs of knowledge bases to search (multi-KB support)", + "type": "array", + "items": { + "type": "string" + } + }, + "knowledge_ids": { + "description": "IDs of specific knowledge (files) to search", + "type": "array", + "items": { + "type": "string" + } + }, + "query": { + "description": "Query text to search for", + "type": "string" + } + } + }, + "handler_session.StopSessionRequest": { + "type": "object", + "required": [ + "message_id" + ], + "properties": { + "message_id": { + "type": "string" + } + } + }, + "handler_session.batchDeleteRequest": { + "type": "object", + "properties": { + "delete_all": { + "type": "boolean" + }, + "ids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "types.ASRConfig": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "language": { + "description": "optional: language hint for transcription", + "type": "string" + }, + "model_id": { + "type": "string" + } + } + }, + "types.AgentConfig": { "type": "object", "properties": { "allowed_skills": { @@ -8798,10 +10017,14 @@ "web_search_max_results": { "description": "Maximum number of web search results (default: 5)", "type": "integer" + }, + "web_search_provider_id": { + "description": "WebSearchProviderEntity ID (resolved from agent config)", + "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.AgentStep": { + "types.AgentStep": { "type": "object", "properties": { "iteration": { @@ -8820,12 +10043,12 @@ "description": "Tools called in this step (Act phase)", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall" + "$ref": "#/definitions/types.ToolCall" } } } }, - "github_com_Tencent_WeKnora_internal_types.AnswerStrategy": { + "types.AnswerStrategy": { "type": "string", "enum": [ "all", @@ -8836,7 +10059,7 @@ "AnswerStrategyRandom" ] }, - "github_com_Tencent_WeKnora_internal_types.COSEngineConfig": { + "types.COSEngineConfig": { "type": "object", "properties": { "app_id": { @@ -8859,7 +10082,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig": { + "types.ChatHistoryConfig": { "type": "object", "properties": { "embedding_model_id": { @@ -8876,7 +10099,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ChunkingConfig": { + "types.ChunkingConfig": { "type": "object", "properties": { "child_chunk_size": { @@ -8907,7 +10130,7 @@ "description": "ParserEngineRules configures which parser engine to use for each file type.\nWhen empty, the builtin engine is used for all types.", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule" + "$ref": "#/definitions/types.ParserEngineRule" } }, "separators": { @@ -8919,7 +10142,52 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy": { + "types.ConnectionConfig": { + "type": "object", + "properties": { + "addr": { + "description": "Common", + "type": "string" + }, + "api_key": { + "description": "AES-GCM encrypted", + "type": "string" + }, + "grpc_address": { + "description": "Weaviate", + "type": "string" + }, + "host": { + "description": "Qdrant", + "type": "string" + }, + "password": { + "description": "AES-GCM encrypted", + "type": "string" + }, + "port": { + "type": "integer" + }, + "scheme": { + "type": "string" + }, + "use_default_connection": { + "description": "Postgres", + "type": "boolean" + }, + "use_tls": { + "type": "boolean" + }, + "username": { + "type": "string" + }, + "version": { + "description": "Version is the detected server version (e.g., \"7.10.1\", \"16.2\", \"1.12.6\").\nAuto-populated by TestConnection on successful connectivity check.", + "type": "string" + } + } + }, + "types.ContextCompressionStrategy": { "type": "string", "enum": [ "sliding_window", @@ -8930,14 +10198,14 @@ "ContextCompressionSmart" ] }, - "github_com_Tencent_WeKnora_internal_types.ContextConfig": { + "types.ContextConfig": { "type": "object", "properties": { "compression_strategy": { "description": "Compression strategy: \"sliding_window\" or \"smart\"", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy" + "$ref": "#/definitions/types.ContextCompressionStrategy" } ] }, @@ -8955,7 +10223,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ConversationConfig": { + "types.ConversationConfig": { "type": "object", "properties": { "context_template": { @@ -9025,7 +10293,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest": { + "types.CreateOrganizationRequest": { "type": "object", "required": [ "name" @@ -9055,7 +10323,15 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.CustomAgentConfig": { + "types.CredentialsConfig": { + "type": "object", + "properties": { + "weknoracloud": { + "$ref": "#/definitions/types.WeKnoraCloudCredentials" + } + } + }, + "types.CustomAgentConfig": { "type": "object", "properties": { "agent_mode": { @@ -9069,6 +10345,14 @@ "type": "string" } }, + "asr_model_id": { + "description": "ASR model ID for audio transcription (optional)", + "type": "string" + }, + "audio_upload_enabled": { + "description": "Whether audio upload (ASR transcription) is enabled for this agent (default: false)", + "type": "boolean" + }, "context_template": { "description": "Context template for normal mode (how to format retrieved chunks)", "type": "string" @@ -9140,6 +10424,10 @@ "type": "string" } }, + "llm_call_timeout": { + "description": "Timeout for a single LLM call in seconds (0 = use global default)", + "type": "integer" + }, "max_completion_tokens": { "description": "Maximum completion tokens (only for normal mode)", "type": "integer" @@ -9240,6 +10528,14 @@ "description": "VLM model ID for image analysis (optional, falls back to tenant-level VLM)", "type": "string" }, + "web_fetch_enabled": { + "description": "Whether to auto-fetch full page content for reranked web search results", + "type": "boolean" + }, + "web_fetch_top_n": { + "description": "Max number of pages to fetch after rerank (default: 3)", + "type": "integer" + }, "web_search_enabled": { "description": "===== Web Search Settings =====\nWhether web search is enabled", "type": "boolean" @@ -9247,10 +10543,14 @@ "web_search_max_results": { "description": "Maximum web search results", "type": "integer" + }, + "web_search_provider_id": { + "description": "WebSearchProviderID references a specific WebSearchProviderEntity.\nIf empty, the tenant's default provider (is_default=true) is used.", + "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.DataSource": { + "types.DataSource": { "type": "object", "properties": { "config": { @@ -9310,7 +10610,7 @@ "description": "Latest sync log (not stored in DB, populated on query)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog" + "$ref": "#/definitions/types.SyncLog" } ] }, @@ -9356,7 +10656,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.EmbeddingParameters": { + "types.EmbeddingParameters": { "type": "object", "properties": { "dimension": { @@ -9367,7 +10667,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ExtractConfig": { + "types.ExtractConfig": { "type": "object", "properties": { "enabled": { @@ -9376,13 +10676,13 @@ "nodes": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode" + "$ref": "#/definitions/types.GraphNode" } }, "relations": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation" + "$ref": "#/definitions/types.GraphRelation" } }, "tags": { @@ -9396,7 +10696,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload": { + "types.FAQBatchUpsertPayload": { "type": "object", "required": [ "entries" @@ -9409,7 +10709,7 @@ "entries": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload" + "$ref": "#/definitions/types.FAQEntryPayload" } }, "knowledge_id": { @@ -9428,32 +10728,32 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQConfig": { + "types.FAQConfig": { "type": "object", "properties": { "index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode" + "$ref": "#/definitions/types.FAQIndexMode" }, "question_index_mode": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode" + "$ref": "#/definitions/types.FAQQuestionIndexMode" } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate": { + "types.FAQEntryFieldsBatchUpdate": { "type": "object", "properties": { "by_id": { "description": "ByID 按条目ID更新,key为条目ID (seq_id)", "type": "object", "additionalProperties": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsUpdate" } }, "by_tag": { "description": "ByTag 按Tag批量更新,key为TagID (seq_id)", "type": "object", "additionalProperties": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate" + "$ref": "#/definitions/types.FAQEntryFieldsUpdate" } }, "exclude_ids": { @@ -9465,7 +10765,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate": { + "types.FAQEntryFieldsUpdate": { "type": "object", "properties": { "is_enabled": { @@ -9479,14 +10779,14 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQEntryPayload": { + "types.FAQEntryPayload": { "type": "object", "required": [ "standard_question" ], "properties": { "answer_strategy": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AnswerStrategy" + "$ref": "#/definitions/types.AnswerStrategy" }, "answers": { "type": "array", @@ -9527,7 +10827,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.FAQIndexMode": { + "types.FAQIndexMode": { "type": "string", "enum": [ "question_only", @@ -9538,7 +10838,7 @@ "FAQIndexModeQuestionAnswer" ] }, - "github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode": { + "types.FAQQuestionIndexMode": { "type": "string", "enum": [ "combined", @@ -9549,7 +10849,7 @@ "FAQQuestionIndexModeSeparate" ] }, - "github_com_Tencent_WeKnora_internal_types.FAQSearchRequest": { + "types.FAQSearchRequest": { "type": "object", "required": [ "query_text" @@ -9584,7 +10884,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.GraphNode": { + "types.GraphNode": { "type": "object", "properties": { "attributes": { @@ -9604,7 +10904,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.GraphRelation": { + "types.GraphRelation": { "type": "object", "properties": { "node1": { @@ -9618,7 +10918,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig": { + "types.ImageProcessingConfig": { "type": "object", "properties": { "model_id": { @@ -9627,7 +10927,32 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.InviteMemberRequest": { + "types.IndexConfig": { + "type": "object", + "properties": { + "collection_name": { + "description": "Milvus", + "type": "string" + }, + "collection_prefix": { + "description": "Qdrant", + "type": "string" + }, + "index_name": { + "description": "ES, OpenSearch", + "type": "string" + }, + "number_of_replicas": { + "description": "ES, OpenSearch", + "type": "integer" + }, + "number_of_shards": { + "description": "ES, OpenSearch", + "type": "integer" + } + } + }, + "types.InviteMemberRequest": { "type": "object", "required": [ "role", @@ -9638,7 +10963,7 @@ "description": "Role to assign: admin/editor/viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] }, @@ -9648,7 +10973,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest": { + "types.JoinByOrganizationIDRequest": { "type": "object", "required": [ "organization_id" @@ -9666,13 +10991,13 @@ "description": "Optional: requested role (admin/editor/viewer); default viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest": { + "types.JoinOrganizationRequest": { "type": "object", "required": [ "invite_code" @@ -9685,7 +11010,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.Knowledge": { + "types.Knowledge": { "type": "object", "properties": { "channel": { @@ -9808,9 +11133,17 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBase": { + "types.KnowledgeBase": { "type": "object", "properties": { + "asr_config": { + "description": "ASR config (Automatic Speech Recognition)", + "allOf": [ + { + "$ref": "#/definitions/types.ASRConfig" + } + ] + }, "chunk_count": { "description": "Chunk count (not stored in database, calculated on query)", "type": "integer" @@ -9819,7 +11152,7 @@ "description": "Chunking configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + "$ref": "#/definitions/types.ChunkingConfig" } ] }, @@ -9847,7 +11180,7 @@ "description": "Extract config", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig" + "$ref": "#/definitions/types.ExtractConfig" } ] }, @@ -9855,7 +11188,7 @@ "description": "FAQConfig stores FAQ specific configuration such as indexing strategy", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + "$ref": "#/definitions/types.FAQConfig" } ] }, @@ -9867,7 +11200,7 @@ "description": "Image processing configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + "$ref": "#/definitions/types.ImageProcessingConfig" } ] }, @@ -9903,7 +11236,7 @@ "description": "QuestionGenerationConfig stores question generation configuration for document knowledge bases", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig" + "$ref": "#/definitions/types.QuestionGenerationConfig" } ] }, @@ -9915,7 +11248,7 @@ "description": "Deprecated: legacy COS config column. Kept for backward compatibility with old data.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageConfig" + "$ref": "#/definitions/types.StorageConfig" } ] }, @@ -9923,7 +11256,7 @@ "description": "Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageProviderConfig" + "$ref": "#/definitions/types.StorageProviderConfig" } ] }, @@ -9947,20 +11280,20 @@ "description": "VLM config", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" + "$ref": "#/definitions/types.VLMConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig": { + "types.KnowledgeBaseConfig": { "type": "object", "properties": { "chunking_config": { "description": "Chunking configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig" + "$ref": "#/definitions/types.ChunkingConfig" } ] }, @@ -9968,7 +11301,7 @@ "description": "FAQ configuration (only for FAQ type knowledge bases)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig" + "$ref": "#/definitions/types.FAQConfig" } ] }, @@ -9976,13 +11309,13 @@ "description": "Image processing configuration", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig" + "$ref": "#/definitions/types.ImageProcessingConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse": { + "types.KnowledgeBaseShareResponse": { "type": "object", "properties": { "chunk_count": { @@ -10038,13 +11371,13 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ListMembersResponse": { + "types.ListMembersResponse": { "type": "object", "properties": { "members": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse" + "$ref": "#/definitions/types.OrganizationMemberResponse" } }, "total": { @@ -10052,20 +11385,20 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse": { + "types.ListOrganizationsResponse": { "type": "object", "properties": { "organizations": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationResponse" + "$ref": "#/definitions/types.OrganizationResponse" } }, "resource_counts": { "description": "各空间内知识库/智能体数量,供列表侧栏展示", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse" + "$ref": "#/definitions/types.ResourceCountsByOrgResponse" } ] }, @@ -10074,13 +11407,13 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ListSharesResponse": { + "types.ListSharesResponse": { "type": "object", "properties": { "shares": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse" + "$ref": "#/definitions/types.KnowledgeBaseShareResponse" } }, "total": { @@ -10088,7 +11421,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.LocalEngineConfig": { + "types.LocalEngineConfig": { "type": "object", "properties": { "path_prefix": { @@ -10096,7 +11429,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.LoginRequest": { + "types.LoginRequest": { "type": "object", "required": [ "email", @@ -10112,7 +11445,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.LoginResponse": { + "types.LoginResponse": { "type": "object", "properties": { "message": { @@ -10125,17 +11458,17 @@ "type": "boolean" }, "tenant": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" }, "token": { "type": "string" }, "user": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.User" + "$ref": "#/definitions/types.User" } } }, - "github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig": { + "types.MCPAdvancedConfig": { "type": "object", "properties": { "retry_count": { @@ -10152,7 +11485,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPAuthConfig": { + "types.MCPAuthConfig": { "type": "object", "properties": { "api_key": { @@ -10169,26 +11502,26 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPEnvVars": { + "types.MCPEnvVars": { "type": "object", "additionalProperties": { "type": "string" } }, - "github_com_Tencent_WeKnora_internal_types.MCPHeaders": { + "types.MCPHeaders": { "type": "object", "additionalProperties": { "type": "string" } }, - "github_com_Tencent_WeKnora_internal_types.MCPService": { + "types.MCPService": { "type": "object", "properties": { "advanced_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig" + "$ref": "#/definitions/types.MCPAdvancedConfig" }, "auth_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAuthConfig" + "$ref": "#/definitions/types.MCPAuthConfig" }, "created_at": { "type": "string" @@ -10206,12 +11539,12 @@ "description": "Environment variables for stdio", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPEnvVars" + "$ref": "#/definitions/types.MCPEnvVars" } ] }, "headers": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPHeaders" + "$ref": "#/definitions/types.MCPHeaders" }, "id": { "type": "string" @@ -10227,7 +11560,7 @@ "description": "Required for stdio transport", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPStdioConfig" + "$ref": "#/definitions/types.MCPStdioConfig" } ] }, @@ -10235,7 +11568,7 @@ "type": "integer" }, "transport_type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MCPTransportType" + "$ref": "#/definitions/types.MCPTransportType" }, "updated_at": { "type": "string" @@ -10246,7 +11579,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPStdioConfig": { + "types.MCPStdioConfig": { "type": "object", "properties": { "args": { @@ -10262,7 +11595,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MCPTransportType": { + "types.MCPTransportType": { "type": "string", "enum": [ "sse", @@ -10285,7 +11618,7 @@ "MCPTransportStdio" ] }, - "github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload": { + "types.ManualKnowledgePayload": { "type": "object", "properties": { "channel": { @@ -10305,7 +11638,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MatchType": { + "types.MatchType": { "type": "integer", "enum": [ 0, @@ -10351,7 +11684,7 @@ "MatchTypeDataAnalysis" ] }, - "github_com_Tencent_WeKnora_internal_types.MentionedItem": { + "types.MentionedItem": { "type": "object", "properties": { "id": { @@ -10370,7 +11703,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.Message": { + "types.Message": { "type": "object", "properties": { "agent_duration_ms": { @@ -10381,7 +11714,14 @@ "description": "Agent execution steps (only for assistant messages generated by agent)\nThis contains the detailed reasoning process and tool calls made by the agent\nStored for user history display, but NOT included in LLM context to avoid redundancy", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AgentStep" + "$ref": "#/definitions/types.AgentStep" + } + }, + "attachments": { + "description": "Attached files (documents, audio, etc., for user messages)", + "type": "array", + "items": { + "$ref": "#/definitions/types.MessageAttachment" } }, "channel": { @@ -10412,7 +11752,7 @@ "description": "Attached images with OCR/Caption text (for user messages)", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MessageImage" + "$ref": "#/definitions/types.MessageImage" } }, "is_completed": { @@ -10431,14 +11771,14 @@ "description": "References to knowledge chunks used in the response", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SearchResult" + "$ref": "#/definitions/types.SearchResult" } }, "mentioned_items": { "description": "Mentioned knowledge bases and files (for user messages)\nStores the @mentioned items when user sends a message", "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem" + "$ref": "#/definitions/types.MentionedItem" } }, "request_id": { @@ -10459,7 +11799,40 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MessageImage": { + "types.MessageAttachment": { + "type": "object", + "properties": { + "content": { + "description": "Extracted text content (for small text files)", + "type": "string" + }, + "file_name": { + "description": "Original filename", + "type": "string" + }, + "file_size": { + "description": "File size in bytes", + "type": "integer" + }, + "file_type": { + "description": "File extension (e.g., \".pdf\", \".docx\")", + "type": "string" + }, + "is_truncated": { + "description": "Whether content was truncated", + "type": "boolean" + }, + "line_count": { + "description": "Total line count (for text files)", + "type": "integer" + }, + "url": { + "description": "Storage URL (provider://path)", + "type": "string" + } + } + }, + "types.MessageImage": { "type": "object", "properties": { "caption": { @@ -10470,7 +11843,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig": { + "types.MinIOEngineConfig": { "type": "object", "properties": { "access_key_id": { @@ -10497,17 +11870,25 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ModelParameters": { + "types.ModelParameters": { "type": "object", "properties": { "api_key": { "type": "string" }, + "app_id": { + "description": "WeKnoraCloud 厂商专用凭证", + "type": "string" + }, + "app_secret": { + "description": "AES-256 加密存储,实际承载上游 API Key", + "type": "string" + }, "base_url": { "type": "string" }, "embedding_parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.EmbeddingParameters" + "$ref": "#/definitions/types.EmbeddingParameters" }, "extra_config": { "description": "Provider-specific configuration", @@ -10533,7 +11914,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ModelSource": { + "types.ModelSource": { "type": "string", "enum": [ "local", @@ -10551,10 +11932,12 @@ "jina", "openrouter", "nvidia", - "novita" + "novita", + "azure_openai" ], "x-enum-comments": { "ModelSourceAliyun": "Aliyun DashScope model", + "ModelSourceAzureOpenAI": "Azure OpenAI model", "ModelSourceDeepseek": "Deepseek model", "ModelSourceGemini": "Gemini model", "ModelSourceHunyuan": "Hunyuan model", @@ -10587,7 +11970,8 @@ "Jina AI model", "OpenRouter model", "NVIDIA model", - "Novita AI model" + "Novita AI model", + "Azure OpenAI model" ], "x-enum-varnames": [ "ModelSourceLocal", @@ -10605,18 +11989,21 @@ "ModelSourceJina", "ModelSourceOpenRouter", "ModelSourceNvidia", - "ModelSourceNovita" + "ModelSourceNovita", + "ModelSourceAzureOpenAI" ] }, - "github_com_Tencent_WeKnora_internal_types.ModelType": { + "types.ModelType": { "type": "string", "enum": [ "Embedding", "Rerank", "KnowledgeQA", - "VLLM" + "VLLM", + "ASR" ], "x-enum-comments": { + "ModelTypeASR": "ASR (Automatic Speech Recognition) model", "ModelTypeEmbedding": "Embedding model", "ModelTypeKnowledgeQA": "KnowledgeQA model", "ModelTypeRerank": "Rerank model", @@ -10626,16 +12013,18 @@ "Embedding model", "Rerank model", "KnowledgeQA model", - "VLLM model" + "VLLM model", + "ASR (Automatic Speech Recognition) model" ], "x-enum-varnames": [ "ModelTypeEmbedding", "ModelTypeRerank", "ModelTypeKnowledgeQA", - "ModelTypeVLLM" + "ModelTypeVLLM", + "ModelTypeASR" ] }, - "github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse": { + "types.OIDCAuthURLResponse": { "type": "object", "properties": { "authorization_url": { @@ -10652,7 +12041,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse": { + "types.OIDCConfigResponse": { "type": "object", "properties": { "enabled": { @@ -10666,7 +12055,39 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.OrgMemberRole": { + "types.OSSEngineConfig": { + "type": "object", + "properties": { + "access_key": { + "type": "string" + }, + "bucket_name": { + "type": "string" + }, + "endpoint": { + "type": "string" + }, + "path_prefix": { + "type": "string" + }, + "region": { + "type": "string" + }, + "secret_key": { + "type": "string" + }, + "temp_bucket_name": { + "type": "string" + }, + "temp_region": { + "type": "string" + }, + "use_temp_bucket": { + "type": "boolean" + } + } + }, + "types.OrgMemberRole": { "type": "string", "enum": [ "admin", @@ -10679,7 +12100,7 @@ "OrgRoleViewer" ] }, - "github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse": { + "types.OrganizationMemberResponse": { "type": "object", "properties": { "avatar": { @@ -10708,7 +12129,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.OrganizationResponse": { + "types.OrganizationResponse": { "type": "object", "properties": { "agent_share_count": { @@ -10778,13 +12199,9 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ParserEngineConfig": { + "types.ParserEngineConfig": { "type": "object", "properties": { - "docreader_addr": { - "description": "文档解析服务地址", - "type": "string" - }, "mineru_api_key": { "description": "MinerU 云 API Key", "type": "string" @@ -10827,7 +12244,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ParserEngineRule": { + "types.ParserEngineRule": { "type": "object", "properties": { "engine": { @@ -10841,7 +12258,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig": { + "types.QuestionGenerationConfig": { "type": "object", "properties": { "enabled": { @@ -10853,7 +12270,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.RegisterRequest": { + "types.RegisterRequest": { "type": "object", "required": [ "email", @@ -10875,7 +12292,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.RegisterResponse": { + "types.RegisterResponse": { "type": "object", "properties": { "message": { @@ -10885,14 +12302,14 @@ "type": "boolean" }, "tenant": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" }, "user": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.User" + "$ref": "#/definitions/types.User" } } }, - "github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest": { + "types.RequestRoleUpgradeRequest": { "type": "object", "required": [ "requested_role" @@ -10907,13 +12324,13 @@ "description": "The role user wants to upgrade to", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.Resource": { + "types.Resource": { "type": "object", "properties": { "description": { @@ -10924,6 +12341,10 @@ "description": "Unique identifier in the external system", "type": "string" }, + "has_children": { + "description": "Whether this resource has children that can be expanded", + "type": "boolean" + }, "metadata": { "description": "Additional metadata", "type": "object", @@ -10951,7 +12372,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse": { + "types.ResourceCountsByOrgResponse": { "type": "object", "properties": { "agents": { @@ -10978,7 +12399,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.RetrievalConfig": { + "types.RetrievalConfig": { "type": "object", "properties": { "embedding_top_k": { @@ -11007,14 +12428,14 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams": { + "types.RetrieverEngineParams": { "type": "object", "properties": { "retriever_engine_type": { "description": "Retriever engine type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineType" + "$ref": "#/definitions/types.RetrieverEngineType" } ] }, @@ -11022,13 +12443,13 @@ "description": "Retriever type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverType" + "$ref": "#/definitions/types.RetrieverType" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngineType": { + "types.RetrieverEngineType": { "type": "string", "enum": [ "postgres", @@ -11051,18 +12472,18 @@ "SQLiteRetrieverEngineType" ] }, - "github_com_Tencent_WeKnora_internal_types.RetrieverEngines": { + "types.RetrieverEngines": { "type": "object", "properties": { "engines": { "type": "array", "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams" + "$ref": "#/definitions/types.RetrieverEngineParams" } } } }, - "github_com_Tencent_WeKnora_internal_types.RetrieverType": { + "types.RetrieverType": { "type": "string", "enum": [ "keywords", @@ -11085,7 +12506,7 @@ "WebSearchRetrieverType" ] }, - "github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest": { + "types.ReviewJoinRequestRequest": { "type": "object", "properties": { "approved": { @@ -11099,13 +12520,13 @@ "description": "Optional: role to assign when approving; overrides applicant's requested role", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.S3EngineConfig": { + "types.S3EngineConfig": { "type": "object", "properties": { "access_key": { @@ -11128,7 +12549,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.SearchParams": { + "types.SearchParams": { "type": "object", "properties": { "disable_keywords_match": { @@ -11184,7 +12605,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.SearchResult": { + "types.SearchResult": { "type": "object", "properties": { "chunk_index": { @@ -11250,7 +12671,7 @@ "description": "Match type", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MatchType" + "$ref": "#/definitions/types.MatchType" } ] }, @@ -11290,7 +12711,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.Session": { + "types.Session": { "type": "object", "properties": { "created_at": { @@ -11320,7 +12741,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest": { + "types.ShareKnowledgeBaseRequest": { "type": "object", "required": [ "organization_id", @@ -11331,11 +12752,11 @@ "type": "string" }, "permission": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.StorageConfig": { + "types.StorageConfig": { "type": "object", "properties": { "app_id": { @@ -11361,40 +12782,43 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.StorageEngineConfig": { + "types.StorageEngineConfig": { "type": "object", "properties": { "cos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig" + "$ref": "#/definitions/types.COSEngineConfig" }, "default_provider": { - "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\"", + "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", "type": "string" }, "local": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.LocalEngineConfig" + "$ref": "#/definitions/types.LocalEngineConfig" }, "minio": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig" + "$ref": "#/definitions/types.MinIOEngineConfig" + }, + "oss": { + "$ref": "#/definitions/types.OSSEngineConfig" }, "s3": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig" + "$ref": "#/definitions/types.S3EngineConfig" }, "tos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig" + "$ref": "#/definitions/types.TOSEngineConfig" } } }, - "github_com_Tencent_WeKnora_internal_types.StorageProviderConfig": { + "types.StorageProviderConfig": { "type": "object", "properties": { "provider": { - "description": "\"local\", \"minio\", \"cos\", \"tos\"", + "description": "\"local\", \"minio\", \"cos\", \"tos\", \"s3\", \"oss\"", "type": "string" } } }, - "github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest": { + "types.SubmitJoinRequestRequest": { "type": "object", "required": [ "invite_code" @@ -11413,13 +12837,13 @@ "description": "Optional: role the applicant requests (admin/editor/viewer); default viewer", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.SyncLog": { + "types.SyncLog": { "type": "object", "properties": { "created_at": { @@ -11491,7 +12915,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.TOSEngineConfig": { + "types.TOSEngineConfig": { "type": "object", "properties": { "access_key": { @@ -11514,14 +12938,14 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.Tenant": { + "types.Tenant": { "type": "object", "properties": { "agent_config": { "description": "Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.\nThis field is kept for backward compatibility and will be removed in future versions.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AgentConfig" + "$ref": "#/definitions/types.AgentConfig" } ] }, @@ -11537,7 +12961,7 @@ "description": "Chat history config: knowledge base configuration for indexing and searching chat messages via vector search", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig" + "$ref": "#/definitions/types.ChatHistoryConfig" } ] }, @@ -11545,7 +12969,7 @@ "description": "Global Context configuration for this tenant (default for all sessions)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ContextConfig" + "$ref": "#/definitions/types.ContextConfig" } ] }, @@ -11553,7 +12977,7 @@ "description": "Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.\nThis field is kept for backward compatibility and will be removed in future versions.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ConversationConfig" + "$ref": "#/definitions/types.ConversationConfig" } ] }, @@ -11561,6 +12985,14 @@ "description": "Creation time", "type": "string" }, + "credentials": { + "description": "Credentials config: third-party provider credentials (e.g. WeKnoraCloud AppID/AppSecret)", + "allOf": [ + { + "$ref": "#/definitions/types.CredentialsConfig" + } + ] + }, "deleted_at": { "description": "Deletion time", "allOf": [ @@ -11585,7 +13017,7 @@ "description": "Parser engine config overrides (MinerU endpoint, API key, etc.). Used when parsing documents; overrides env.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineConfig" + "$ref": "#/definitions/types.ParserEngineConfig" } ] }, @@ -11593,7 +13025,7 @@ "description": "Retrieval config: global search/retrieval parameters shared by knowledge search and message search", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrievalConfig" + "$ref": "#/definitions/types.RetrievalConfig" } ] }, @@ -11601,7 +13033,7 @@ "description": "Retriever engines", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngines" + "$ref": "#/definitions/types.RetrieverEngines" } ] }, @@ -11613,7 +13045,7 @@ "description": "Storage engine config: parameters for Local, MinIO, COS. Used for document/file storage and docreader.", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.StorageEngineConfig" + "$ref": "#/definitions/types.StorageEngineConfig" } ] }, @@ -11633,13 +13065,13 @@ "description": "Global WebSearch configuration for this tenant", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.WebSearchConfig" + "$ref": "#/definitions/types.WebSearchConfig" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.ToolCall": { + "types.ToolCall": { "type": "object", "properties": { "args": { @@ -11667,13 +13099,13 @@ "description": "Execution result (contains Output)", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolResult" + "$ref": "#/definitions/types.ToolResult" } ] } } }, - "github_com_Tencent_WeKnora_internal_types.ToolResult": { + "types.ToolResult": { "type": "object", "properties": { "data": { @@ -11702,18 +13134,18 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest": { + "types.UpdateMemberRoleRequest": { "type": "object", "required": [ "role" ], "properties": { "role": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest": { + "types.UpdateOrganizationRequest": { "type": "object", "properties": { "avatar": { @@ -11747,18 +13179,18 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest": { + "types.UpdateSharePermissionRequest": { "type": "object", "required": [ "permission" ], "properties": { "permission": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole" + "$ref": "#/definitions/types.OrgMemberRole" } } }, - "github_com_Tencent_WeKnora_internal_types.User": { + "types.User": { "type": "object", "properties": { "avatar": { @@ -11797,7 +13229,7 @@ "description": "Association relationship, not stored in the database", "allOf": [ { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant" + "$ref": "#/definitions/types.Tenant" } ] }, @@ -11815,7 +13247,7 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.VLMConfig": { + "types.VLMConfig": { "type": "object", "properties": { "api_key": { @@ -11842,11 +13274,22 @@ } } }, - "github_com_Tencent_WeKnora_internal_types.WebSearchConfig": { + "types.WeKnoraCloudCredentials": { + "type": "object", + "properties": { + "app_id": { + "type": "string" + }, + "app_secret": { + "type": "string" + } + } + }, + "types.WebSearchConfig": { "type": "object", "properties": { "api_key": { - "description": "API密钥(如果需要)", + "description": "Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.", "type": "string" }, "blacklist": { @@ -11881,7 +13324,7 @@ "type": "integer" }, "provider": { - "description": "搜索引擎提供商ID", + "description": "Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.", "type": "string" }, "rerank_model_id": { @@ -11889,731 +13332,6 @@ "type": "string" } } - }, - "gorm.DeletedAt": { - "type": "object", - "properties": { - "time": { - "type": "string" - }, - "valid": { - "description": "Valid is true if Time is not NULL", - "type": "boolean" - } - } - }, - "internal_handler.CopyKnowledgeBaseRequest": { - "type": "object", - "required": [ - "source_id" - ], - "properties": { - "source_id": { - "type": "string" - }, - "target_id": { - "type": "string" - }, - "task_id": { - "type": "string" - } - } - }, - "internal_handler.CreateAgentRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "avatar": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.CreateModelRequest": { - "type": "object", - "required": [ - "name", - "parameters", - "source", - "type" - ], - "properties": { - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters" - }, - "source": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource" - }, - "type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType" - } - } - }, - "internal_handler.DeleteTagRequest": { - "type": "object", - "properties": { - "exclude_ids": { - "description": "Chunk seq_ids to exclude from deletion", - "type": "array", - "items": { - "type": "integer" - } - } - } - }, - "internal_handler.EvaluationRequest": { - "type": "object", - "properties": { - "chat_id": { - "description": "ID of chat model to use", - "type": "string" - }, - "dataset_id": { - "description": "ID of dataset to evaluate", - "type": "string" - }, - "knowledge_base_id": { - "description": "ID of knowledge base to use", - "type": "string" - }, - "rerank_id": { - "description": "ID of rerank model to use", - "type": "string" - } - } - }, - "internal_handler.FabriTextRequest": { - "type": "object", - "required": [ - "model_id" - ], - "properties": { - "model_id": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "internal_handler.GetStorageEngineStatusResponse": { - "type": "object", - "properties": { - "engines": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler.StorageEngineStatusItem" - } - }, - "minio_env_available": { - "type": "boolean" - } - } - }, - "internal_handler.GetSystemInfoResponse": { - "type": "object", - "properties": { - "build_time": { - "type": "string" - }, - "commit_id": { - "type": "string" - }, - "db_version": { - "type": "string" - }, - "edition": { - "type": "string" - }, - "go_version": { - "type": "string" - }, - "graph_database_engine": { - "type": "string" - }, - "keyword_index_engine": { - "type": "string" - }, - "minio_enabled": { - "type": "boolean" - }, - "vector_store_engine": { - "type": "string" - }, - "version": { - "type": "string" - } - } - }, - "internal_handler.KBModelConfigRequest": { - "type": "object", - "required": [ - "embeddingModelId", - "llmModelId" - ], - "properties": { - "documentSplitting": { - "description": "文档分块配置", - "type": "object", - "properties": { - "childChunkSize": { - "type": "integer" - }, - "chunkOverlap": { - "type": "integer" - }, - "chunkSize": { - "type": "integer" - }, - "enableParentChild": { - "type": "boolean" - }, - "parentChunkSize": { - "type": "integer" - }, - "parserEngineRules": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule" - } - }, - "separators": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "embeddingModelId": { - "type": "string" - }, - "llmModelId": { - "type": "string" - }, - "multimodal": { - "description": "多模态配置(仅模型相关;存储引擎在 storageProvider 中配置)", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - } - } - }, - "nodeExtract": { - "description": "知识图谱配置", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - }, - "nodes": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode" - } - }, - "relations": { - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation" - } - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "text": { - "type": "string" - } - } - }, - "questionGeneration": { - "description": "问题生成配置", - "type": "object", - "properties": { - "enabled": { - "type": "boolean" - }, - "questionCount": { - "type": "integer" - } - } - }, - "storageProvider": { - "description": "存储引擎选择(\"local\" | \"minio\" | \"cos\"),影响文档上传与文档内图片存储,参数从全局设置读取", - "type": "string" - }, - "vlm_config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig" - } - } - }, - "internal_handler.ListMinioBucketsResponse": { - "type": "object", - "properties": { - "buckets": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler.MinioBucketInfo" - } - } - } - }, - "internal_handler.MinioBucketInfo": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "name": { - "type": "string" - }, - "policy": { - "description": "\"public\", \"private\", \"custom\"", - "type": "string" - } - } - }, - "internal_handler.RemoteModelCheckRequest": { - "type": "object", - "required": [ - "baseUrl", - "modelName" - ], - "properties": { - "apiKey": { - "type": "string" - }, - "baseUrl": { - "type": "string" - }, - "modelName": { - "type": "string" - } - } - }, - "internal_handler.SearchMessagesRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "limit": { - "description": "Maximum number of results to return (default: 20)", - "type": "integer" - }, - "mode": { - "description": "Search mode: \"keyword\", \"vector\", \"hybrid\" (default: \"hybrid\")", - "type": "string" - }, - "query": { - "description": "Query text for search", - "type": "string" - }, - "session_ids": { - "description": "Filter by specific session IDs (optional)", - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "internal_handler.StorageCheckRequest": { - "type": "object", - "properties": { - "cos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig" - }, - "minio": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig" - }, - "provider": { - "description": "\"minio\", \"cos\", \"tos\", or \"s3\"", - "type": "string" - }, - "s3": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig" - }, - "tos": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig" - } - } - }, - "internal_handler.StorageCheckResponse": { - "type": "object", - "properties": { - "bucket_created": { - "type": "boolean" - }, - "message": { - "type": "string" - }, - "ok": { - "type": "boolean" - } - } - }, - "internal_handler.StorageEngineStatusItem": { - "type": "object", - "properties": { - "available": { - "description": "whether the engine can be used", - "type": "boolean" - }, - "description": { - "description": "short description for UI", - "type": "string" - }, - "name": { - "description": "\"local\", \"minio\", \"cos\", \"tos\"", - "type": "string" - } - } - }, - "internal_handler.TextRelationExtractionRequest": { - "type": "object", - "required": [ - "model_id", - "tags", - "text" - ], - "properties": { - "model_id": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "text": { - "type": "string" - } - } - }, - "internal_handler.UpdateAgentRequest": { - "type": "object", - "properties": { - "avatar": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.UpdateChunkRequest": { - "type": "object", - "properties": { - "chunk_index": { - "type": "integer" - }, - "content": { - "type": "string" - }, - "embedding": { - "type": "array", - "items": { - "type": "number" - } - }, - "end_at": { - "type": "integer" - }, - "image_info": { - "type": "string" - }, - "is_enabled": { - "type": "boolean" - }, - "start_at": { - "type": "integer" - } - } - }, - "internal_handler.UpdateKnowledgeBaseRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "config": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig" - }, - "description": { - "type": "string" - }, - "name": { - "type": "string" - } - } - }, - "internal_handler.UpdateModelRequest": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "name": { - "type": "string" - }, - "parameters": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters" - }, - "source": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource" - }, - "type": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType" - } - } - }, - "internal_handler.addSimilarQuestionsRequest": { - "type": "object", - "required": [ - "similar_questions" - ], - "properties": { - "similar_questions": { - "type": "array", - "minItems": 1, - "items": { - "type": "string" - } - } - } - }, - "internal_handler.updateLastFAQImportResultDisplayStatusRequest": { - "type": "object", - "required": [ - "display_status" - ], - "properties": { - "display_status": { - "type": "string", - "enum": [ - "open", - "close" - ] - } - } - }, - "internal_handler_session.CreateKnowledgeQARequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "agent_enabled": { - "description": "Whether agent mode is enabled for this request", - "type": "boolean" - }, - "agent_id": { - "description": "Selected custom agent ID (backend resolves shared agent and its tenant from share relation)", - "type": "string" - }, - "channel": { - "description": "Source channel: \"web\", \"api\", \"im\", etc.", - "type": "string" - }, - "disable_title": { - "description": "Whether to disable auto title generation", - "type": "boolean" - }, - "enable_memory": { - "description": "Whether memory feature is enabled for this request", - "type": "boolean" - }, - "images": { - "description": "Attached images for multimodal chat", - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.ImageAttachment" - } - }, - "knowledge_base_ids": { - "description": "Selected knowledge base ID for this request", - "type": "array", - "items": { - "type": "string" - } - }, - "knowledge_ids": { - "description": "Selected knowledge ID for this request", - "type": "array", - "items": { - "type": "string" - } - }, - "mentioned_items": { - "description": "@mentioned knowledge bases and files", - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.MentionedItemRequest" - } - }, - "query": { - "description": "Query text for knowledge base search", - "type": "string" - }, - "summary_model_id": { - "description": "Optional summary model ID for this request (overrides session default)", - "type": "string" - }, - "web_search_enabled": { - "description": "Whether web search is enabled for this request", - "type": "boolean" - } - } - }, - "internal_handler_session.CreateSessionRequest": { - "type": "object", - "properties": { - "description": { - "description": "Description for the session (optional)", - "type": "string" - }, - "title": { - "description": "Title for the session (optional)", - "type": "string" - } - } - }, - "internal_handler_session.GenerateTitleRequest": { - "type": "object", - "required": [ - "messages" - ], - "properties": { - "messages": { - "description": "Messages to use as context for title generation", - "type": "array", - "items": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.Message" - } - } - } - }, - "internal_handler_session.ImageAttachment": { - "type": "object", - "properties": { - "caption": { - "description": "VLM analysis result (context-aware, single call)", - "type": "string" - }, - "data": { - "description": "base64 data URI from frontend (data:image/png;base64,...)", - "type": "string" - }, - "url": { - "description": "serving URL after saving to storage", - "type": "string" - } - } - }, - "internal_handler_session.MentionedItemRequest": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "kb_type": { - "description": "\"document\" or \"faq\" (only for kb type)", - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "description": "\"kb\" for knowledge base, \"file\" for file", - "type": "string" - } - } - }, - "internal_handler_session.SearchKnowledgeRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "knowledge_base_id": { - "description": "Single knowledge base ID (for backward compatibility)", - "type": "string" - }, - "knowledge_base_ids": { - "description": "IDs of knowledge bases to search (multi-KB support)", - "type": "array", - "items": { - "type": "string" - } - }, - "knowledge_ids": { - "description": "IDs of specific knowledge (files) to search", - "type": "array", - "items": { - "type": "string" - } - }, - "query": { - "description": "Query text to search for", - "type": "string" - } - } - }, - "internal_handler_session.StopSessionRequest": { - "type": "object", - "required": [ - "message_id" - ], - "properties": { - "message_id": { - "type": "string" - } - } - }, - "internal_handler_session.batchDeleteRequest": { - "type": "object", - "properties": { - "delete_all": { - "type": "boolean" - }, - "ids": { - "type": "array", - "items": { - "type": "string" - } - } - } } }, "securityDefinitions": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index ae6ca15c..ccb6fcdb 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1,6 +1,6 @@ basePath: /api/v1 definitions: - github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata: + datasource.ConnectorMetadata: properties: auth_type: description: '"oauth2", "api_key", "token", etc.' @@ -22,15 +22,15 @@ definitions: type: type: string type: object - github_com_Tencent_WeKnora_internal_errors.AppError: + errors.AppError: properties: code: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.ErrorCode' + $ref: '#/definitions/errors.ErrorCode' details: {} message: type: string type: object - github_com_Tencent_WeKnora_internal_errors.ErrorCode: + errors.ErrorCode: enum: - 1000 - 1001 @@ -74,7 +74,554 @@ definitions: - ErrAgentMissingAllowedTools - ErrAgentInvalidMaxIterations - ErrAgentInvalidTemperature - github_com_Tencent_WeKnora_internal_types.AgentConfig: + github_com_Tencent_WeKnora_internal_errors.AppError: + properties: + code: + $ref: '#/definitions/errors.ErrorCode' + details: {} + message: + type: string + type: object + gorm.DeletedAt: + properties: + time: + type: string + valid: + description: Valid is true if Time is not NULL + type: boolean + type: object + handler.CopyKnowledgeBaseRequest: + properties: + source_id: + type: string + target_id: + type: string + task_id: + type: string + required: + - source_id + type: object + handler.CreateAgentRequest: + properties: + avatar: + type: string + config: + $ref: '#/definitions/types.CustomAgentConfig' + description: + type: string + name: + type: string + required: + - name + type: object + handler.CreateModelRequest: + properties: + description: + type: string + name: + type: string + parameters: + $ref: '#/definitions/types.ModelParameters' + source: + $ref: '#/definitions/types.ModelSource' + type: + $ref: '#/definitions/types.ModelType' + required: + - name + - parameters + - source + - type + type: object + handler.CreateStoreRequest: + properties: + connection_config: + $ref: '#/definitions/types.ConnectionConfig' + engine_type: + $ref: '#/definitions/types.RetrieverEngineType' + index_config: + $ref: '#/definitions/types.IndexConfig' + name: + type: string + required: + - connection_config + - engine_type + - name + type: object + handler.DeleteTagRequest: + properties: + exclude_ids: + description: Chunk seq_ids to exclude from deletion + items: + type: integer + type: array + type: object + handler.EvaluationRequest: + properties: + chat_id: + description: ID of chat model to use + type: string + dataset_id: + description: ID of dataset to evaluate + type: string + knowledge_base_id: + description: ID of knowledge base to use + type: string + rerank_id: + description: ID of rerank model to use + type: string + type: object + handler.FabriTextRequest: + properties: + model_id: + type: string + tags: + items: + type: string + type: array + required: + - model_id + type: object + handler.GetStorageEngineStatusResponse: + properties: + engines: + items: + $ref: '#/definitions/handler.StorageEngineStatusItem' + type: array + minio_env_available: + type: boolean + type: object + handler.GetSystemInfoResponse: + properties: + build_time: + type: string + commit_id: + type: string + db_version: + type: string + edition: + type: string + go_version: + type: string + graph_database_engine: + type: string + keyword_index_engine: + type: string + minio_enabled: + type: boolean + vector_store_engine: + type: string + version: + type: string + type: object + handler.KBModelConfigRequest: + properties: + asr_config: + $ref: '#/definitions/types.ASRConfig' + documentSplitting: + description: 文档分块配置 + properties: + childChunkSize: + type: integer + chunkOverlap: + type: integer + chunkSize: + type: integer + enableParentChild: + type: boolean + parentChunkSize: + type: integer + parserEngineRules: + items: + $ref: '#/definitions/types.ParserEngineRule' + type: array + separators: + items: + type: string + type: array + type: object + embeddingModelId: + type: string + llmModelId: + type: string + multimodal: + description: 多模态配置(仅模型相关;存储引擎在 storageProvider 中配置) + properties: + enabled: + type: boolean + type: object + nodeExtract: + description: 知识图谱配置 + properties: + enabled: + type: boolean + nodes: + items: + $ref: '#/definitions/types.GraphNode' + type: array + relations: + items: + $ref: '#/definitions/types.GraphRelation' + type: array + tags: + items: + type: string + type: array + text: + type: string + type: object + questionGeneration: + description: 问题生成配置 + properties: + enabled: + type: boolean + questionCount: + type: integer + type: object + storageProvider: + description: 存储引擎选择("local" | "minio" | "cos"),影响文档上传与文档内图片存储,参数从全局设置读取 + type: string + vlm_config: + $ref: '#/definitions/types.VLMConfig' + required: + - embeddingModelId + - llmModelId + type: object + handler.RemoteModelCheckRequest: + properties: + apiKey: + type: string + baseUrl: + type: string + modelName: + type: string + provider: + type: string + required: + - baseUrl + - modelName + type: object + handler.SearchMessagesRequest: + properties: + limit: + description: 'Maximum number of results to return (default: 20)' + type: integer + mode: + description: 'Search mode: "keyword", "vector", "hybrid" (default: "hybrid")' + type: string + query: + description: Query text for search + type: string + session_ids: + description: Filter by specific session IDs (optional) + items: + type: string + type: array + required: + - query + type: object + handler.StorageCheckRequest: + properties: + cos: + $ref: '#/definitions/types.COSEngineConfig' + minio: + $ref: '#/definitions/types.MinIOEngineConfig' + oss: + $ref: '#/definitions/types.OSSEngineConfig' + provider: + description: '"minio", "cos", "tos", "s3", "oss"' + type: string + s3: + $ref: '#/definitions/types.S3EngineConfig' + tos: + $ref: '#/definitions/types.TOSEngineConfig' + type: object + handler.StorageCheckResponse: + properties: + bucket_created: + type: boolean + message: + type: string + ok: + type: boolean + type: object + handler.StorageEngineStatusItem: + properties: + available: + description: whether the engine can be used + type: boolean + description: + description: short description for UI + type: string + name: + description: '"local", "minio", "cos", "tos"' + type: string + type: object + handler.TestStoreRequest: + properties: + connection_config: + $ref: '#/definitions/types.ConnectionConfig' + engine_type: + $ref: '#/definitions/types.RetrieverEngineType' + required: + - connection_config + - engine_type + type: object + handler.TextRelationExtractionRequest: + properties: + model_id: + type: string + tags: + items: + type: string + type: array + text: + type: string + required: + - model_id + - tags + - text + type: object + handler.UpdateAgentRequest: + properties: + avatar: + type: string + config: + $ref: '#/definitions/types.CustomAgentConfig' + description: + type: string + name: + type: string + type: object + handler.UpdateChunkRequest: + properties: + chunk_index: + type: integer + content: + type: string + embedding: + items: + type: number + type: array + end_at: + type: integer + image_info: + type: string + is_enabled: + type: boolean + start_at: + type: integer + type: object + handler.UpdateKnowledgeBaseRequest: + properties: + config: + $ref: '#/definitions/types.KnowledgeBaseConfig' + description: + type: string + name: + type: string + required: + - name + type: object + handler.UpdateModelRequest: + properties: + description: + type: string + name: + type: string + parameters: + $ref: '#/definitions/types.ModelParameters' + source: + $ref: '#/definitions/types.ModelSource' + type: + $ref: '#/definitions/types.ModelType' + type: object + handler.UpdateStoreRequest: + properties: + name: + type: string + required: + - name + type: object + handler.addSimilarQuestionsRequest: + properties: + similar_questions: + items: + type: string + minItems: 1 + type: array + required: + - similar_questions + type: object + handler.updateLastFAQImportResultDisplayStatusRequest: + properties: + display_status: + enum: + - open + - close + type: string + required: + - display_status + type: object + handler_session.AttachmentUpload: + properties: + data: + description: Base64-encoded file content + type: string + file_name: + description: Original filename + type: string + file_size: + description: File size in bytes + type: integer + type: object + handler_session.CreateKnowledgeQARequest: + properties: + agent_enabled: + description: Whether agent mode is enabled for this request + type: boolean + agent_id: + description: Selected custom agent ID (backend resolves shared agent and its + tenant from share relation) + type: string + attachment_uploads: + description: Attached files (documents, audio, etc.) + items: + $ref: '#/definitions/handler_session.AttachmentUpload' + type: array + channel: + description: 'Source channel: "web", "api", "im", etc.' + type: string + disable_title: + description: Whether to disable auto title generation + type: boolean + enable_memory: + description: Whether memory feature is enabled for this request + type: boolean + images: + description: Attached images for multimodal chat + items: + $ref: '#/definitions/handler_session.ImageAttachment' + type: array + knowledge_base_ids: + description: Selected knowledge base ID for this request + items: + type: string + type: array + knowledge_ids: + description: Selected knowledge ID for this request + items: + type: string + type: array + mentioned_items: + description: '@mentioned knowledge bases and files' + items: + $ref: '#/definitions/handler_session.MentionedItemRequest' + type: array + query: + description: Query text for knowledge base search + type: string + summary_model_id: + description: Optional summary model ID for this request (overrides session + default) + type: string + web_search_enabled: + description: Whether web search is enabled for this request + type: boolean + required: + - query + type: object + handler_session.CreateSessionRequest: + properties: + description: + description: Description for the session (optional) + type: string + title: + description: Title for the session (optional) + type: string + type: object + handler_session.GenerateTitleRequest: + properties: + messages: + description: Messages to use as context for title generation + items: + $ref: '#/definitions/types.Message' + type: array + required: + - messages + type: object + handler_session.ImageAttachment: + properties: + caption: + description: VLM analysis result (context-aware, single call) + type: string + data: + description: base64 data URI from frontend (data:image/png;base64,...) + type: string + url: + description: serving URL after saving to storage + type: string + type: object + handler_session.MentionedItemRequest: + properties: + id: + type: string + kb_type: + description: '"document" or "faq" (only for kb type)' + type: string + name: + type: string + type: + description: '"kb" for knowledge base, "file" for file' + type: string + type: object + handler_session.SearchKnowledgeRequest: + properties: + knowledge_base_id: + description: Single knowledge base ID (for backward compatibility) + type: string + knowledge_base_ids: + description: IDs of knowledge bases to search (multi-KB support) + items: + type: string + type: array + knowledge_ids: + description: IDs of specific knowledge (files) to search + items: + type: string + type: array + query: + description: Query text to search for + type: string + required: + - query + type: object + handler_session.StopSessionRequest: + properties: + message_id: + type: string + required: + - message_id + type: object + handler_session.batchDeleteRequest: + properties: + delete_all: + type: boolean + ids: + items: + type: string + type: array + type: object + types.ASRConfig: + properties: + enabled: + type: boolean + language: + description: 'optional: language hint for transcription' + type: string + model_id: + type: string + type: object + types.AgentConfig: properties: allowed_skills: description: Skill names whitelist (empty = allow all) @@ -172,8 +719,11 @@ definitions: web_search_max_results: description: 'Maximum number of web search results (default: 5)' type: integer + web_search_provider_id: + description: WebSearchProviderEntity ID (resolved from agent config) + type: string type: object - github_com_Tencent_WeKnora_internal_types.AgentStep: + types.AgentStep: properties: iteration: description: Iteration number (0-indexed) @@ -187,10 +737,10 @@ definitions: tool_calls: description: Tools called in this step (Act phase) items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall' + $ref: '#/definitions/types.ToolCall' type: array type: object - github_com_Tencent_WeKnora_internal_types.AnswerStrategy: + types.AnswerStrategy: enum: - all - random @@ -198,7 +748,7 @@ definitions: x-enum-varnames: - AnswerStrategyAll - AnswerStrategyRandom - github_com_Tencent_WeKnora_internal_types.COSEngineConfig: + types.COSEngineConfig: properties: app_id: type: string @@ -213,7 +763,7 @@ definitions: secret_key: type: string type: object - github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig: + types.ChatHistoryConfig: properties: embedding_model_id: description: |- @@ -229,7 +779,7 @@ definitions: This is set internally when the feature is first enabled; users should not set this directly. type: string type: object - github_com_Tencent_WeKnora_internal_types.ChunkingConfig: + types.ChunkingConfig: properties: child_chunk_size: description: |- @@ -262,7 +812,7 @@ definitions: ParserEngineRules configures which parser engine to use for each file type. When empty, the builtin engine is used for all types. items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule' + $ref: '#/definitions/types.ParserEngineRule' type: array separators: description: Separators @@ -270,7 +820,41 @@ definitions: type: string type: array type: object - github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy: + types.ConnectionConfig: + properties: + addr: + description: Common + type: string + api_key: + description: AES-GCM encrypted + type: string + grpc_address: + description: Weaviate + type: string + host: + description: Qdrant + type: string + password: + description: AES-GCM encrypted + type: string + port: + type: integer + scheme: + type: string + use_default_connection: + description: Postgres + type: boolean + use_tls: + type: boolean + username: + type: string + version: + description: |- + Version is the detected server version (e.g., "7.10.1", "16.2", "1.12.6"). + Auto-populated by TestConnection on successful connectivity check. + type: string + type: object + types.ContextCompressionStrategy: enum: - sliding_window - smart @@ -278,11 +862,11 @@ definitions: x-enum-varnames: - ContextCompressionSlidingWindow - ContextCompressionSmart - github_com_Tencent_WeKnora_internal_types.ContextConfig: + types.ContextConfig: properties: compression_strategy: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ContextCompressionStrategy' + - $ref: '#/definitions/types.ContextCompressionStrategy' description: 'Compression strategy: "sliding_window" or "smart"' max_tokens: description: Maximum tokens allowed in LLM context @@ -296,7 +880,7 @@ definitions: description: 'Summarize threshold: number of messages before summarization' type: integer type: object - github_com_Tencent_WeKnora_internal_types.ConversationConfig: + types.ConversationConfig: properties: context_template: description: ContextTemplate is the prompt template for summarizing retrieval @@ -346,7 +930,7 @@ definitions: vector_threshold: type: number type: object - github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest: + types.CreateOrganizationRequest: properties: avatar: description: optional avatar URL @@ -368,7 +952,12 @@ definitions: required: - name type: object - github_com_Tencent_WeKnora_internal_types.CustomAgentConfig: + types.CredentialsConfig: + properties: + weknoracloud: + $ref: '#/definitions/types.WeKnoraCloudCredentials' + type: object + types.CustomAgentConfig: properties: agent_mode: description: |- @@ -380,6 +969,13 @@ definitions: items: type: string type: array + asr_model_id: + description: ASR model ID for audio transcription (optional) + type: string + audio_upload_enabled: + description: 'Whether audio upload (ASR transcription) is enabled for this + agent (default: false)' + type: boolean context_template: description: Context template for normal mode (how to format retrieved chunks) type: string @@ -429,7 +1025,7 @@ definitions: type: integer image_storage_provider: description: |- - Storage provider for image uploads: "local", "minio", "cos", "tos", "s3", "oss" + Storage provider for image uploads: "local", "minio", "cos", "tos" Empty means use the global/tenant default provider. type: string image_upload_enabled: @@ -451,6 +1047,9 @@ definitions: items: type: string type: array + llm_call_timeout: + description: Timeout for a single LLM call in seconds (0 = use global default) + type: integer max_completion_tokens: description: Maximum completion tokens (only for normal mode) type: integer @@ -549,6 +1148,13 @@ definitions: description: VLM model ID for image analysis (optional, falls back to tenant-level VLM) type: string + web_fetch_enabled: + description: Whether to auto-fetch full page content for reranked web search + results + type: boolean + web_fetch_top_n: + description: 'Max number of pages to fetch after rerank (default: 3)' + type: integer web_search_enabled: description: |- ===== Web Search Settings ===== @@ -557,8 +1163,13 @@ definitions: web_search_max_results: description: Maximum web search results type: integer + web_search_provider_id: + description: |- + WebSearchProviderID references a specific WebSearchProviderEntity. + If empty, the tenant's default provider (is_default=true) is used. + type: string type: object - github_com_Tencent_WeKnora_internal_types.DataSource: + types.DataSource: properties: config: description: |- @@ -601,7 +1212,7 @@ definitions: type: array latest_sync_log: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog' + - $ref: '#/definitions/types.SyncLog' description: Latest sync log (not stored in DB, populated on query) name: description: User-friendly name @@ -635,24 +1246,24 @@ definitions: description: Last update timestamp type: string type: object - github_com_Tencent_WeKnora_internal_types.EmbeddingParameters: + types.EmbeddingParameters: properties: dimension: type: integer truncate_prompt_tokens: type: integer type: object - github_com_Tencent_WeKnora_internal_types.ExtractConfig: + types.ExtractConfig: properties: enabled: type: boolean nodes: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode' + $ref: '#/definitions/types.GraphNode' type: array relations: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation' + $ref: '#/definitions/types.GraphRelation' type: array tags: items: @@ -661,14 +1272,14 @@ definitions: text: type: string type: object - github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload: + types.FAQBatchUpsertPayload: properties: dry_run: description: 仅验证,不实际导入 type: boolean entries: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload' + $ref: '#/definitions/types.FAQEntryPayload' type: array knowledge_id: type: string @@ -683,23 +1294,23 @@ definitions: required: - entries type: object - github_com_Tencent_WeKnora_internal_types.FAQConfig: + types.FAQConfig: properties: index_mode: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQIndexMode' + $ref: '#/definitions/types.FAQIndexMode' question_index_mode: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode' + $ref: '#/definitions/types.FAQQuestionIndexMode' type: object - github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate: + types.FAQEntryFieldsBatchUpdate: properties: by_id: additionalProperties: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate' + $ref: '#/definitions/types.FAQEntryFieldsUpdate' description: ByID 按条目ID更新,key为条目ID (seq_id) type: object by_tag: additionalProperties: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate' + $ref: '#/definitions/types.FAQEntryFieldsUpdate' description: ByTag 按Tag批量更新,key为TagID (seq_id) type: object exclude_ids: @@ -708,7 +1319,7 @@ definitions: type: integer type: array type: object - github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsUpdate: + types.FAQEntryFieldsUpdate: properties: is_enabled: type: boolean @@ -717,10 +1328,10 @@ definitions: tag_id: type: integer type: object - github_com_Tencent_WeKnora_internal_types.FAQEntryPayload: + types.FAQEntryPayload: properties: answer_strategy: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AnswerStrategy' + $ref: '#/definitions/types.AnswerStrategy' answers: items: type: string @@ -749,7 +1360,7 @@ definitions: required: - standard_question type: object - github_com_Tencent_WeKnora_internal_types.FAQIndexMode: + types.FAQIndexMode: enum: - question_only - question_answer @@ -757,7 +1368,7 @@ definitions: x-enum-varnames: - FAQIndexModeQuestionOnly - FAQIndexModeQuestionAnswer - github_com_Tencent_WeKnora_internal_types.FAQQuestionIndexMode: + types.FAQQuestionIndexMode: enum: - combined - separate @@ -765,7 +1376,7 @@ definitions: x-enum-varnames: - FAQQuestionIndexModeCombined - FAQQuestionIndexModeSeparate - github_com_Tencent_WeKnora_internal_types.FAQSearchRequest: + types.FAQSearchRequest: properties: first_priority_tag_ids: description: 第一优先级标签ID列表,限定命中范围,优先级最高 @@ -789,7 +1400,7 @@ definitions: required: - query_text type: object - github_com_Tencent_WeKnora_internal_types.GraphNode: + types.GraphNode: properties: attributes: items: @@ -802,7 +1413,7 @@ definitions: name: type: string type: object - github_com_Tencent_WeKnora_internal_types.GraphRelation: + types.GraphRelation: properties: node1: type: string @@ -811,17 +1422,35 @@ definitions: type: type: string type: object - github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig: + types.ImageProcessingConfig: properties: model_id: description: Model ID type: string type: object - github_com_Tencent_WeKnora_internal_types.InviteMemberRequest: + types.IndexConfig: + properties: + collection_name: + description: Milvus + type: string + collection_prefix: + description: Qdrant + type: string + index_name: + description: ES, OpenSearch + type: string + number_of_replicas: + description: ES, OpenSearch + type: integer + number_of_shards: + description: ES, OpenSearch + type: integer + type: object + types.InviteMemberRequest: properties: role: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + - $ref: '#/definitions/types.OrgMemberRole' description: 'Role to assign: admin/editor/viewer' user_id: description: User ID to invite @@ -830,7 +1459,7 @@ definitions: - role - user_id type: object - github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest: + types.JoinByOrganizationIDRequest: properties: message: description: Optional message for join request @@ -840,12 +1469,12 @@ definitions: type: string role: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + - $ref: '#/definitions/types.OrgMemberRole' description: 'Optional: requested role (admin/editor/viewer); default viewer' required: - organization_id type: object - github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest: + types.JoinOrganizationRequest: properties: invite_code: maxLength: 32 @@ -854,7 +1483,7 @@ definitions: required: - invite_code type: object - github_com_Tencent_WeKnora_internal_types.Knowledge: + types.Knowledge: properties: channel: description: Channel indicates through which channel the knowledge was ingested @@ -945,14 +1574,18 @@ definitions: description: Last updated time of the knowledge type: string type: object - github_com_Tencent_WeKnora_internal_types.KnowledgeBase: + types.KnowledgeBase: properties: + asr_config: + allOf: + - $ref: '#/definitions/types.ASRConfig' + description: ASR config (Automatic Speech Recognition) chunk_count: description: Chunk count (not stored in database, calculated on query) type: integer chunking_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' + - $ref: '#/definitions/types.ChunkingConfig' description: Chunking configuration created_at: description: Creation time of the knowledge base @@ -969,11 +1602,11 @@ definitions: type: string extract_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ExtractConfig' + - $ref: '#/definitions/types.ExtractConfig' description: Extract config faq_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' + - $ref: '#/definitions/types.FAQConfig' description: FAQConfig stores FAQ specific configuration such as indexing strategy id: @@ -981,7 +1614,7 @@ definitions: type: string image_processing_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig' + - $ref: '#/definitions/types.ImageProcessingConfig' description: Image processing configuration is_pinned: description: Whether this knowledge base is pinned to the top of the list @@ -1009,7 +1642,7 @@ definitions: type: integer question_generation_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig' + - $ref: '#/definitions/types.QuestionGenerationConfig' description: QuestionGenerationConfig stores question generation configuration for document knowledge bases share_count: @@ -1018,12 +1651,12 @@ definitions: type: integer storage_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.StorageConfig' + - $ref: '#/definitions/types.StorageConfig' description: 'Deprecated: legacy COS config column. Kept for backward compatibility with old data.' storage_provider_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.StorageProviderConfig' + - $ref: '#/definitions/types.StorageProviderConfig' description: 'Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig' summary_model_id: @@ -1040,25 +1673,25 @@ definitions: type: string vlm_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig' + - $ref: '#/definitions/types.VLMConfig' description: VLM config type: object - github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig: + types.KnowledgeBaseConfig: properties: chunking_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChunkingConfig' + - $ref: '#/definitions/types.ChunkingConfig' description: Chunking configuration faq_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQConfig' + - $ref: '#/definitions/types.FAQConfig' description: FAQ configuration (only for FAQ type knowledge bases) image_processing_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ImageProcessingConfig' + - $ref: '#/definitions/types.ImageProcessingConfig' description: Image processing configuration type: object - github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse: + types.KnowledgeBaseShareResponse: properties: chunk_count: type: integer @@ -1096,43 +1729,43 @@ definitions: source_tenant_id: type: integer type: object - github_com_Tencent_WeKnora_internal_types.ListMembersResponse: + types.ListMembersResponse: properties: members: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse' + $ref: '#/definitions/types.OrganizationMemberResponse' type: array total: type: integer type: object - github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse: + types.ListOrganizationsResponse: properties: organizations: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrganizationResponse' + $ref: '#/definitions/types.OrganizationResponse' type: array resource_counts: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse' + - $ref: '#/definitions/types.ResourceCountsByOrgResponse' description: 各空间内知识库/智能体数量,供列表侧栏展示 total: type: integer type: object - github_com_Tencent_WeKnora_internal_types.ListSharesResponse: + types.ListSharesResponse: properties: shares: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseShareResponse' + $ref: '#/definitions/types.KnowledgeBaseShareResponse' type: array total: type: integer type: object - github_com_Tencent_WeKnora_internal_types.LocalEngineConfig: + types.LocalEngineConfig: properties: path_prefix: type: string type: object - github_com_Tencent_WeKnora_internal_types.LoginRequest: + types.LoginRequest: properties: email: type: string @@ -1143,7 +1776,7 @@ definitions: - email - password type: object - github_com_Tencent_WeKnora_internal_types.LoginResponse: + types.LoginResponse: properties: message: type: string @@ -1152,13 +1785,13 @@ definitions: success: type: boolean tenant: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant' + $ref: '#/definitions/types.Tenant' token: type: string user: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.User' + $ref: '#/definitions/types.User' type: object - github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig: + types.MCPAdvancedConfig: properties: retry_count: description: 'Number of retries, default: 3' @@ -1170,7 +1803,7 @@ definitions: description: 'Timeout in seconds, default: 30' type: integer type: object - github_com_Tencent_WeKnora_internal_types.MCPAuthConfig: + types.MCPAuthConfig: properties: api_key: type: string @@ -1181,20 +1814,20 @@ definitions: token: type: string type: object - github_com_Tencent_WeKnora_internal_types.MCPEnvVars: + types.MCPEnvVars: additionalProperties: type: string type: object - github_com_Tencent_WeKnora_internal_types.MCPHeaders: + types.MCPHeaders: additionalProperties: type: string type: object - github_com_Tencent_WeKnora_internal_types.MCPService: + types.MCPService: properties: advanced_config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAdvancedConfig' + $ref: '#/definitions/types.MCPAdvancedConfig' auth_config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPAuthConfig' + $ref: '#/definitions/types.MCPAuthConfig' created_at: type: string deleted_at: @@ -1205,10 +1838,10 @@ definitions: type: boolean env_vars: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPEnvVars' + - $ref: '#/definitions/types.MCPEnvVars' description: Environment variables for stdio headers: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPHeaders' + $ref: '#/definitions/types.MCPHeaders' id: type: string is_builtin: @@ -1218,19 +1851,19 @@ definitions: type: string stdio_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPStdioConfig' + - $ref: '#/definitions/types.MCPStdioConfig' description: Required for stdio transport tenant_id: type: integer transport_type: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPTransportType' + $ref: '#/definitions/types.MCPTransportType' updated_at: type: string url: description: 'Optional: required for SSE/HTTP Streamable' type: string type: object - github_com_Tencent_WeKnora_internal_types.MCPStdioConfig: + types.MCPStdioConfig: properties: args: description: Command arguments array @@ -1241,7 +1874,7 @@ definitions: description: 'Command: "uvx" or "npx"' type: string type: object - github_com_Tencent_WeKnora_internal_types.MCPTransportType: + types.MCPTransportType: enum: - sse - http-streamable @@ -1259,7 +1892,7 @@ definitions: - MCPTransportSSE - MCPTransportHTTPStreamable - MCPTransportStdio - github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload: + types.ManualKnowledgePayload: properties: channel: type: string @@ -1272,7 +1905,7 @@ definitions: title: type: string type: object - github_com_Tencent_WeKnora_internal_types.MatchType: + types.MatchType: enum: - 0 - 1 @@ -1313,7 +1946,7 @@ definitions: - MatchTypeWebSearch - MatchTypeDirectLoad - MatchTypeDataAnalysis - github_com_Tencent_WeKnora_internal_types.MentionedItem: + types.MentionedItem: properties: id: type: string @@ -1326,7 +1959,7 @@ definitions: description: '"kb" for knowledge base, "file" for file' type: string type: object - github_com_Tencent_WeKnora_internal_types.Message: + types.Message: properties: agent_duration_ms: description: Agent total execution duration in milliseconds (from query start @@ -1338,7 +1971,12 @@ definitions: This contains the detailed reasoning process and tool calls made by the agent Stored for user history display, but NOT included in LLM context to avoid redundancy items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AgentStep' + $ref: '#/definitions/types.AgentStep' + type: array + attachments: + description: Attached files (documents, audio, etc., for user messages) + items: + $ref: '#/definitions/types.MessageAttachment' type: array channel: description: Channel indicates the source channel of this message (e.g., "web", @@ -1360,7 +1998,7 @@ definitions: images: description: Attached images with OCR/Caption text (for user messages) items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MessageImage' + $ref: '#/definitions/types.MessageImage' type: array is_completed: description: Whether message generation is complete @@ -1377,14 +2015,14 @@ definitions: knowledge_references: description: References to knowledge chunks used in the response items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SearchResult' + $ref: '#/definitions/types.SearchResult' type: array mentioned_items: description: |- Mentioned knowledge bases and files (for user messages) Stores the @mentioned items when user sends a message items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem' + $ref: '#/definitions/types.MentionedItem' type: array request_id: description: Request identifier for tracking API requests @@ -1399,14 +2037,38 @@ definitions: description: Last update timestamp type: string type: object - github_com_Tencent_WeKnora_internal_types.MessageImage: + types.MessageAttachment: + properties: + content: + description: Extracted text content (for small text files) + type: string + file_name: + description: Original filename + type: string + file_size: + description: File size in bytes + type: integer + file_type: + description: File extension (e.g., ".pdf", ".docx") + type: string + is_truncated: + description: Whether content was truncated + type: boolean + line_count: + description: Total line count (for text files) + type: integer + url: + description: Storage URL (provider://path) + type: string + type: object + types.MessageImage: properties: caption: type: string url: type: string type: object - github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig: + types.MinIOEngineConfig: properties: access_key_id: type: string @@ -1424,14 +2086,20 @@ definitions: use_ssl: type: boolean type: object - github_com_Tencent_WeKnora_internal_types.ModelParameters: + types.ModelParameters: properties: api_key: type: string + app_id: + description: WeKnoraCloud 厂商专用凭证 + type: string + app_secret: + description: AES-256 加密存储,实际承载上游 API Key + type: string base_url: type: string embedding_parameters: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.EmbeddingParameters' + $ref: '#/definitions/types.EmbeddingParameters' extra_config: additionalProperties: type: string @@ -1449,7 +2117,7 @@ definitions: description: Whether the model accepts image/multimodal input type: boolean type: object - github_com_Tencent_WeKnora_internal_types.ModelSource: + types.ModelSource: enum: - local - remote @@ -1467,9 +2135,11 @@ definitions: - openrouter - nvidia - novita + - azure_openai type: string x-enum-comments: ModelSourceAliyun: Aliyun DashScope model + ModelSourceAzureOpenAI: Azure OpenAI model ModelSourceDeepseek: Deepseek model ModelSourceGemini: Gemini model ModelSourceHunyuan: Hunyuan model @@ -1502,6 +2172,7 @@ definitions: - OpenRouter model - NVIDIA model - Novita AI model + - Azure OpenAI model x-enum-varnames: - ModelSourceLocal - ModelSourceRemote @@ -1519,14 +2190,17 @@ definitions: - ModelSourceOpenRouter - ModelSourceNvidia - ModelSourceNovita - github_com_Tencent_WeKnora_internal_types.ModelType: + - ModelSourceAzureOpenAI + types.ModelType: enum: - Embedding - Rerank - KnowledgeQA - VLLM + - ASR type: string x-enum-comments: + ModelTypeASR: ASR (Automatic Speech Recognition) model ModelTypeEmbedding: Embedding model ModelTypeKnowledgeQA: KnowledgeQA model ModelTypeRerank: Rerank model @@ -1536,12 +2210,14 @@ definitions: - Rerank model - KnowledgeQA model - VLLM model + - ASR (Automatic Speech Recognition) model x-enum-varnames: - ModelTypeEmbedding - ModelTypeRerank - ModelTypeKnowledgeQA - ModelTypeVLLM - github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse: + - ModelTypeASR + types.OIDCAuthURLResponse: properties: authorization_url: type: string @@ -1552,7 +2228,7 @@ definitions: success: type: boolean type: object - github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse: + types.OIDCConfigResponse: properties: enabled: type: boolean @@ -1561,7 +2237,28 @@ definitions: success: type: boolean type: object - github_com_Tencent_WeKnora_internal_types.OrgMemberRole: + types.OSSEngineConfig: + properties: + access_key: + type: string + bucket_name: + type: string + endpoint: + type: string + path_prefix: + type: string + region: + type: string + secret_key: + type: string + temp_bucket_name: + type: string + temp_region: + type: string + use_temp_bucket: + type: boolean + type: object + types.OrgMemberRole: enum: - admin - editor @@ -1571,7 +2268,7 @@ definitions: - OrgRoleAdmin - OrgRoleEditor - OrgRoleViewer - github_com_Tencent_WeKnora_internal_types.OrganizationMemberResponse: + types.OrganizationMemberResponse: properties: avatar: type: string @@ -1590,7 +2287,7 @@ definitions: username: type: string type: object - github_com_Tencent_WeKnora_internal_types.OrganizationResponse: + types.OrganizationResponse: properties: agent_share_count: description: 共享到该组织的智能体数量 @@ -1638,11 +2335,8 @@ definitions: updated_at: type: string type: object - github_com_Tencent_WeKnora_internal_types.ParserEngineConfig: + types.ParserEngineConfig: properties: - docreader_addr: - description: 文档解析服务地址 - type: string mineru_api_key: description: MinerU 云 API Key type: string @@ -1672,7 +2366,7 @@ definitions: description: MinerU 自建解析参数 type: string type: object - github_com_Tencent_WeKnora_internal_types.ParserEngineRule: + types.ParserEngineRule: properties: engine: type: string @@ -1681,7 +2375,7 @@ definitions: type: string type: array type: object - github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig: + types.QuestionGenerationConfig: properties: enabled: type: boolean @@ -1690,7 +2384,7 @@ definitions: 10)' type: integer type: object - github_com_Tencent_WeKnora_internal_types.RegisterRequest: + types.RegisterRequest: properties: email: type: string @@ -1706,18 +2400,18 @@ definitions: - password - username type: object - github_com_Tencent_WeKnora_internal_types.RegisterResponse: + types.RegisterResponse: properties: message: type: string success: type: boolean tenant: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant' + $ref: '#/definitions/types.Tenant' user: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.User' + $ref: '#/definitions/types.User' type: object - github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest: + types.RequestRoleUpgradeRequest: properties: message: description: Optional message explaining the reason @@ -1725,12 +2419,12 @@ definitions: type: string requested_role: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + - $ref: '#/definitions/types.OrgMemberRole' description: The role user wants to upgrade to required: - requested_role type: object - github_com_Tencent_WeKnora_internal_types.Resource: + types.Resource: properties: description: description: Optional description @@ -1738,6 +2432,9 @@ definitions: external_id: description: Unique identifier in the external system type: string + has_children: + description: Whether this resource has children that can be expanded + type: boolean metadata: additionalProperties: true description: Additional metadata @@ -1758,7 +2455,7 @@ definitions: description: URL to access in external system type: string type: object - github_com_Tencent_WeKnora_internal_types.ResourceCountsByOrgResponse: + types.ResourceCountsByOrgResponse: properties: agents: properties: @@ -1775,7 +2472,7 @@ definitions: type: object type: object type: object - github_com_Tencent_WeKnora_internal_types.RetrievalConfig: + types.RetrievalConfig: properties: embedding_top_k: description: 'EmbeddingTopK is the maximum number of chunks returned by vector @@ -1802,18 +2499,18 @@ definitions: default: 0.15)' type: number type: object - github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams: + types.RetrieverEngineParams: properties: retriever_engine_type: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineType' + - $ref: '#/definitions/types.RetrieverEngineType' description: Retriever engine type retriever_type: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverType' + - $ref: '#/definitions/types.RetrieverType' description: Retriever type type: object - github_com_Tencent_WeKnora_internal_types.RetrieverEngineType: + types.RetrieverEngineType: enum: - postgres - elasticsearch @@ -1833,14 +2530,14 @@ definitions: - MilvusRetrieverEngineType - WeaviateRetrieverEngineType - SQLiteRetrieverEngineType - github_com_Tencent_WeKnora_internal_types.RetrieverEngines: + types.RetrieverEngines: properties: engines: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngineParams' + $ref: '#/definitions/types.RetrieverEngineParams' type: array type: object - github_com_Tencent_WeKnora_internal_types.RetrieverType: + types.RetrieverType: enum: - keywords - vector @@ -1858,7 +2555,7 @@ definitions: - KeywordsRetrieverType - VectorRetrieverType - WebSearchRetrieverType - github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest: + types.ReviewJoinRequestRequest: properties: approved: type: boolean @@ -1867,11 +2564,11 @@ definitions: type: string role: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + - $ref: '#/definitions/types.OrgMemberRole' description: 'Optional: role to assign when approving; overrides applicant''s requested role' type: object - github_com_Tencent_WeKnora_internal_types.S3EngineConfig: + types.S3EngineConfig: properties: access_key: type: string @@ -1886,7 +2583,7 @@ definitions: secret_key: type: string type: object - github_com_Tencent_WeKnora_internal_types.SearchParams: + types.SearchParams: properties: disable_keywords_match: type: boolean @@ -1930,7 +2627,7 @@ definitions: vector_threshold: type: number type: object - github_com_Tencent_WeKnora_internal_types.SearchResult: + types.SearchResult: properties: chunk_index: description: Chunk index @@ -1984,7 +2681,7 @@ definitions: type: string match_type: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MatchType' + - $ref: '#/definitions/types.MatchType' description: Match type matched_content: description: |- @@ -2014,7 +2711,7 @@ definitions: type: string type: array type: object - github_com_Tencent_WeKnora_internal_types.Session: + types.Session: properties: created_at: type: string @@ -2035,17 +2732,17 @@ definitions: updated_at: type: string type: object - github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest: + types.ShareKnowledgeBaseRequest: properties: organization_id: type: string permission: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + $ref: '#/definitions/types.OrgMemberRole' required: - organization_id - permission type: object - github_com_Tencent_WeKnora_internal_types.StorageConfig: + types.StorageConfig: properties: app_id: type: string @@ -2062,31 +2759,31 @@ definitions: secret_key: type: string type: object - github_com_Tencent_WeKnora_internal_types.StorageEngineConfig: + types.StorageEngineConfig: properties: cos: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig' + $ref: '#/definitions/types.COSEngineConfig' default_provider: description: '"local", "minio", "cos", "tos", "s3", "oss"' type: string local: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.LocalEngineConfig' + $ref: '#/definitions/types.LocalEngineConfig' minio: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig' + $ref: '#/definitions/types.MinIOEngineConfig' oss: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OSSEngineConfig' + $ref: '#/definitions/types.OSSEngineConfig' s3: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig' + $ref: '#/definitions/types.S3EngineConfig' tos: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig' + $ref: '#/definitions/types.TOSEngineConfig' type: object - github_com_Tencent_WeKnora_internal_types.StorageProviderConfig: + types.StorageProviderConfig: properties: provider: description: '"local", "minio", "cos", "tos", "s3", "oss"' type: string type: object - github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest: + types.SubmitJoinRequestRequest: properties: invite_code: maxLength: 32 @@ -2097,13 +2794,13 @@ definitions: type: string role: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + - $ref: '#/definitions/types.OrgMemberRole' description: 'Optional: role the applicant requests (admin/editor/viewer); default viewer' required: - invite_code type: object - github_com_Tencent_WeKnora_internal_types.SyncLog: + types.SyncLog: properties: created_at: description: Creation timestamp (usually same as StartedAt) @@ -2156,7 +2853,7 @@ definitions: description: Last update timestamp type: string type: object - github_com_Tencent_WeKnora_internal_types.TOSEngineConfig: + types.TOSEngineConfig: properties: access_key: type: string @@ -2171,32 +2868,11 @@ definitions: secret_key: type: string type: object - github_com_Tencent_WeKnora_internal_types.OSSEngineConfig: - properties: - access_key: - type: string - bucket_name: - type: string - endpoint: - type: string - path_prefix: - type: string - region: - type: string - secret_key: - type: string - temp_bucket_name: - type: string - temp_region: - type: string - use_temp_bucket: - type: boolean - type: object - github_com_Tencent_WeKnora_internal_types.Tenant: + types.Tenant: properties: agent_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AgentConfig' + - $ref: '#/definitions/types.AgentConfig' description: |- Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead. This field is kept for backward compatibility and will be removed in future versions. @@ -2208,23 +2884,28 @@ definitions: type: string chat_history_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ChatHistoryConfig' + - $ref: '#/definitions/types.ChatHistoryConfig' description: 'Chat history config: knowledge base configuration for indexing and searching chat messages via vector search' context_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ContextConfig' + - $ref: '#/definitions/types.ContextConfig' description: Global Context configuration for this tenant (default for all sessions) conversation_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ConversationConfig' + - $ref: '#/definitions/types.ConversationConfig' description: |- Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead. This field is kept for backward compatibility and will be removed in future versions. created_at: description: Creation time type: string + credentials: + allOf: + - $ref: '#/definitions/types.CredentialsConfig' + description: 'Credentials config: third-party provider credentials (e.g. WeKnoraCloud + AppID/AppSecret)' deleted_at: allOf: - $ref: '#/definitions/gorm.DeletedAt' @@ -2240,24 +2921,24 @@ definitions: type: string parser_engine_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineConfig' + - $ref: '#/definitions/types.ParserEngineConfig' description: Parser engine config overrides (MinerU endpoint, API key, etc.). Used when parsing documents; overrides env. retrieval_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RetrievalConfig' + - $ref: '#/definitions/types.RetrievalConfig' description: 'Retrieval config: global search/retrieval parameters shared by knowledge search and message search' retriever_engines: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RetrieverEngines' + - $ref: '#/definitions/types.RetrieverEngines' description: Retriever engines status: description: Status type: string storage_engine_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.StorageEngineConfig' + - $ref: '#/definitions/types.StorageEngineConfig' description: 'Storage engine config: parameters for Local, MinIO, COS. Used for document/file storage and docreader.' storage_quota: @@ -2272,10 +2953,10 @@ definitions: type: string web_search_config: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WebSearchConfig' + - $ref: '#/definitions/types.WebSearchConfig' description: Global WebSearch configuration for this tenant type: object - github_com_Tencent_WeKnora_internal_types.ToolCall: + types.ToolCall: properties: args: additionalProperties: true @@ -2295,10 +2976,10 @@ definitions: type: string result: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ToolResult' + - $ref: '#/definitions/types.ToolResult' description: Execution result (contains Output) type: object - github_com_Tencent_WeKnora_internal_types.ToolResult: + types.ToolResult: properties: data: additionalProperties: true @@ -2319,14 +3000,14 @@ definitions: description: Whether the tool executed successfully type: boolean type: object - github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest: + types.UpdateMemberRoleRequest: properties: role: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + $ref: '#/definitions/types.OrgMemberRole' required: - role type: object - github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest: + types.UpdateOrganizationRequest: properties: avatar: description: optional avatar URL @@ -2351,14 +3032,14 @@ definitions: description: open for search so others can discover and join type: boolean type: object - github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest: + types.UpdateSharePermissionRequest: properties: permission: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OrgMemberRole' + $ref: '#/definitions/types.OrgMemberRole' required: - permission type: object - github_com_Tencent_WeKnora_internal_types.User: + types.User: properties: avatar: description: Avatar URL of the user @@ -2384,7 +3065,7 @@ definitions: type: boolean tenant: allOf: - - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant' + - $ref: '#/definitions/types.Tenant' description: Association relationship, not stored in the database tenant_id: description: Tenant ID that the user belongs to @@ -2396,7 +3077,7 @@ definitions: description: Username of the user type: string type: object - github_com_Tencent_WeKnora_internal_types.VLMConfig: + types.VLMConfig: properties: api_key: description: API Key @@ -2417,10 +3098,17 @@ definitions: Model Name type: string type: object - github_com_Tencent_WeKnora_internal_types.WebSearchConfig: + types.WeKnoraCloudCredentials: + properties: + app_id: + type: string + app_secret: + type: string + type: object + types.WebSearchConfig: properties: api_key: - description: API密钥(如果需要) + description: 'Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.' type: string blacklist: description: 黑名单规则列表 @@ -2446,505 +3134,12 @@ definitions: description: 最大搜索结果数 type: integer provider: - description: 搜索引擎提供商ID + description: 'Deprecated: Use WebSearchProviderEntity.Parameters.APIKey instead.' type: string rerank_model_id: description: 重排模型ID(用于RAG压缩) type: string type: object - gorm.DeletedAt: - properties: - time: - type: string - valid: - description: Valid is true if Time is not NULL - type: boolean - type: object - internal_handler.CopyKnowledgeBaseRequest: - properties: - source_id: - type: string - target_id: - type: string - task_id: - type: string - required: - - source_id - type: object - internal_handler.CreateAgentRequest: - properties: - avatar: - type: string - config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig' - description: - type: string - name: - type: string - required: - - name - type: object - internal_handler.CreateModelRequest: - properties: - description: - type: string - name: - type: string - parameters: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters' - source: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource' - type: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType' - required: - - name - - parameters - - source - - type - type: object - internal_handler.DeleteTagRequest: - properties: - exclude_ids: - description: Chunk seq_ids to exclude from deletion - items: - type: integer - type: array - type: object - internal_handler.EvaluationRequest: - properties: - chat_id: - description: ID of chat model to use - type: string - dataset_id: - description: ID of dataset to evaluate - type: string - knowledge_base_id: - description: ID of knowledge base to use - type: string - rerank_id: - description: ID of rerank model to use - type: string - type: object - internal_handler.FabriTextRequest: - properties: - model_id: - type: string - tags: - items: - type: string - type: array - required: - - model_id - type: object - internal_handler.GetStorageEngineStatusResponse: - properties: - engines: - items: - $ref: '#/definitions/internal_handler.StorageEngineStatusItem' - type: array - minio_env_available: - type: boolean - type: object - internal_handler.GetSystemInfoResponse: - properties: - build_time: - type: string - commit_id: - type: string - db_version: - type: string - edition: - type: string - go_version: - type: string - graph_database_engine: - type: string - keyword_index_engine: - type: string - minio_enabled: - type: boolean - vector_store_engine: - type: string - version: - type: string - type: object - internal_handler.KBModelConfigRequest: - properties: - documentSplitting: - description: 文档分块配置 - properties: - childChunkSize: - type: integer - chunkOverlap: - type: integer - chunkSize: - type: integer - enableParentChild: - type: boolean - parentChunkSize: - type: integer - parserEngineRules: - items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ParserEngineRule' - type: array - separators: - items: - type: string - type: array - type: object - embeddingModelId: - type: string - llmModelId: - type: string - multimodal: - description: 多模态配置(仅模型相关;存储引擎在 storageProvider 中配置) - properties: - enabled: - type: boolean - type: object - nodeExtract: - description: 知识图谱配置 - properties: - enabled: - type: boolean - nodes: - items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphNode' - type: array - relations: - items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.GraphRelation' - type: array - tags: - items: - type: string - type: array - text: - type: string - type: object - questionGeneration: - description: 问题生成配置 - properties: - enabled: - type: boolean - questionCount: - type: integer - type: object - storageProvider: - description: 存储引擎选择("local" | "minio" | "cos"),影响文档上传与文档内图片存储,参数从全局设置读取 - type: string - vlm_config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.VLMConfig' - required: - - embeddingModelId - - llmModelId - type: object - internal_handler.ListMinioBucketsResponse: - properties: - buckets: - items: - $ref: '#/definitions/internal_handler.MinioBucketInfo' - type: array - type: object - internal_handler.MinioBucketInfo: - properties: - created_at: - type: string - name: - type: string - policy: - description: '"public", "private", "custom"' - type: string - type: object - internal_handler.RemoteModelCheckRequest: - properties: - apiKey: - type: string - baseUrl: - type: string - modelName: - type: string - required: - - baseUrl - - modelName - type: object - internal_handler.SearchMessagesRequest: - properties: - limit: - description: 'Maximum number of results to return (default: 20)' - type: integer - mode: - description: 'Search mode: "keyword", "vector", "hybrid" (default: "hybrid")' - type: string - query: - description: Query text for search - type: string - session_ids: - description: Filter by specific session IDs (optional) - items: - type: string - type: array - required: - - query - type: object - internal_handler.StorageCheckRequest: - properties: - cos: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.COSEngineConfig' - minio: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MinIOEngineConfig' - provider: - description: '"minio", "cos", "tos", "s3", or "oss"' - type: string - oss: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OSSEngineConfig' - s3: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.S3EngineConfig' - tos: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.TOSEngineConfig' - type: object - internal_handler.StorageCheckResponse: - properties: - bucket_created: - type: boolean - message: - type: string - ok: - type: boolean - type: object - internal_handler.StorageEngineStatusItem: - properties: - available: - description: whether the engine can be used - type: boolean - description: - description: short description for UI - type: string - name: - description: '"local", "minio", "cos", "tos", "s3", "oss"' - type: string - type: object - internal_handler.TextRelationExtractionRequest: - properties: - model_id: - type: string - tags: - items: - type: string - type: array - text: - type: string - required: - - model_id - - tags - - text - type: object - internal_handler.UpdateAgentRequest: - properties: - avatar: - type: string - config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.CustomAgentConfig' - description: - type: string - name: - type: string - type: object - internal_handler.UpdateChunkRequest: - properties: - chunk_index: - type: integer - content: - type: string - embedding: - items: - type: number - type: array - end_at: - type: integer - image_info: - type: string - is_enabled: - type: boolean - start_at: - type: integer - type: object - internal_handler.UpdateKnowledgeBaseRequest: - properties: - config: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBaseConfig' - description: - type: string - name: - type: string - required: - - name - type: object - internal_handler.UpdateModelRequest: - properties: - description: - type: string - name: - type: string - parameters: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelParameters' - source: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelSource' - type: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ModelType' - type: object - internal_handler.addSimilarQuestionsRequest: - properties: - similar_questions: - items: - type: string - minItems: 1 - type: array - required: - - similar_questions - type: object - internal_handler.updateLastFAQImportResultDisplayStatusRequest: - properties: - display_status: - enum: - - open - - close - type: string - required: - - display_status - type: object - internal_handler_session.CreateKnowledgeQARequest: - properties: - agent_enabled: - description: Whether agent mode is enabled for this request - type: boolean - agent_id: - description: Selected custom agent ID (backend resolves shared agent and its - tenant from share relation) - type: string - channel: - description: 'Source channel: "web", "api", "im", etc.' - type: string - disable_title: - description: Whether to disable auto title generation - type: boolean - enable_memory: - description: Whether memory feature is enabled for this request - type: boolean - images: - description: Attached images for multimodal chat - items: - $ref: '#/definitions/internal_handler_session.ImageAttachment' - type: array - knowledge_base_ids: - description: Selected knowledge base ID for this request - items: - type: string - type: array - knowledge_ids: - description: Selected knowledge ID for this request - items: - type: string - type: array - mentioned_items: - description: '@mentioned knowledge bases and files' - items: - $ref: '#/definitions/internal_handler_session.MentionedItemRequest' - type: array - query: - description: Query text for knowledge base search - type: string - summary_model_id: - description: Optional summary model ID for this request (overrides session - default) - type: string - web_search_enabled: - description: Whether web search is enabled for this request - type: boolean - required: - - query - type: object - internal_handler_session.CreateSessionRequest: - properties: - description: - description: Description for the session (optional) - type: string - title: - description: Title for the session (optional) - type: string - type: object - internal_handler_session.GenerateTitleRequest: - properties: - messages: - description: Messages to use as context for title generation - items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Message' - type: array - required: - - messages - type: object - internal_handler_session.ImageAttachment: - properties: - caption: - description: VLM analysis result (context-aware, single call) - type: string - data: - description: base64 data URI from frontend (data:image/png;base64,...) - type: string - url: - description: serving URL after saving to storage - type: string - type: object - internal_handler_session.MentionedItemRequest: - properties: - id: - type: string - kb_type: - description: '"document" or "faq" (only for kb type)' - type: string - name: - type: string - type: - description: '"kb" for knowledge base, "file" for file' - type: string - type: object - internal_handler_session.SearchKnowledgeRequest: - properties: - knowledge_base_id: - description: Single knowledge base ID (for backward compatibility) - type: string - knowledge_base_ids: - description: IDs of knowledge bases to search (multi-KB support) - items: - type: string - type: array - knowledge_ids: - description: IDs of specific knowledge (files) to search - items: - type: string - type: array - query: - description: Query text to search for - type: string - required: - - query - type: object - internal_handler_session.StopSessionRequest: - properties: - message_id: - type: string - required: - - message_id - type: object - internal_handler_session.batchDeleteRequest: - properties: - delete_all: - type: boolean - ids: - items: - type: string - type: array - type: object info: contact: name: WeKnora Github @@ -2970,7 +3165,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -2987,7 +3182,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.CreateAgentRequest' + $ref: '#/definitions/handler.CreateAgentRequest' produces: - application/json responses: @@ -2999,7 +3194,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3028,15 +3223,15 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: 无法删除内置智能体 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 智能体不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3064,11 +3259,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 智能体不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3090,7 +3285,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.UpdateAgentRequest' + $ref: '#/definitions/handler.UpdateAgentRequest' produces: - application/json responses: @@ -3102,11 +3297,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: 无法修改内置智能体 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3135,11 +3330,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 智能体不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3180,11 +3375,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 智能体不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3226,7 +3421,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' type: array "400": description: Bad Request @@ -3247,14 +3442,14 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' produces: - application/json responses: "201": description: Created schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' "400": description: Bad Request schema: @@ -3299,7 +3494,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' "404": description: Not Found schema: @@ -3324,14 +3519,14 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.DataSource' + $ref: '#/definitions/types.DataSource' "400": description: Bad Request schema: @@ -3365,7 +3560,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog' + $ref: '#/definitions/types.SyncLog' type: array "400": description: Bad Request @@ -3417,7 +3612,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Resource' + $ref: '#/definitions/types.Resource' type: array "400": description: Bad Request @@ -3466,7 +3661,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog' + $ref: '#/definitions/types.SyncLog' "400": description: Bad Request schema: @@ -3516,7 +3711,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SyncLog' + $ref: '#/definitions/types.SyncLog' "404": description: Not Found schema: @@ -3536,7 +3731,7 @@ paths: description: OK schema: items: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_datasource.ConnectorMetadata' + $ref: '#/definitions/datasource.ConnectorMetadata' type: array summary: Get available connectors tags: @@ -3571,6 +3766,25 @@ paths: summary: Test connection with raw credentials (no persistence) tags: - DataSource + /auth/auto-setup: + post: + consumes: + - application/json + description: Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程 + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/types.LoginResponse' + "403": + description: 非 Lite 版本 + schema: + $ref: '#/definitions/errors.AppError' + summary: 自动初始化(Lite 桌面版) + tags: + - 认证 /auth/change-password: post: consumes: @@ -3599,7 +3813,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 修改密码 @@ -3616,18 +3830,18 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.LoginRequest' + $ref: '#/definitions/types.LoginRequest' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.LoginResponse' + $ref: '#/definitions/types.LoginResponse' "401": description: 认证失败 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' summary: 用户登录 tags: - 认证 @@ -3647,7 +3861,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 用户登出 @@ -3669,7 +3883,7 @@ paths: "401": description: 未授权 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 获取当前用户信息 @@ -3712,7 +3926,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCConfigResponse' + $ref: '#/definitions/types.OIDCConfigResponse' summary: 获取OIDC登录配置 tags: - 认证 @@ -3733,15 +3947,15 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.OIDCAuthURLResponse' + $ref: '#/definitions/types.OIDCAuthURLResponse' "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: OIDC未启用 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' summary: 获取OIDC授权地址 tags: - 认证 @@ -3771,7 +3985,7 @@ paths: "401": description: 令牌无效 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' summary: 刷新令牌 tags: - 认证 @@ -3786,22 +4000,22 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterRequest' + $ref: '#/definitions/types.RegisterRequest' produces: - application/json responses: "201": description: Created schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RegisterResponse' + $ref: '#/definitions/types.RegisterResponse' "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: 注册功能已禁用 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' summary: 用户注册 tags: - 认证 @@ -3821,7 +4035,7 @@ paths: "401": description: 令牌无效 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 验证令牌 @@ -3849,7 +4063,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3887,7 +4101,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3921,11 +4135,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 分块不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3952,7 +4166,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.UpdateChunkRequest' + $ref: '#/definitions/handler.UpdateChunkRequest' produces: - application/json responses: @@ -3964,11 +4178,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 分块不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -3997,11 +4211,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 分块不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4039,11 +4253,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 分块不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4072,7 +4286,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4089,7 +4303,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.EvaluationRequest' + $ref: '#/definitions/handler.EvaluationRequest' produces: - application/json responses: @@ -4101,7 +4315,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4130,7 +4344,7 @@ paths: "404": description: 任务不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4148,7 +4362,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.TextRelationExtractionRequest' + $ref: '#/definitions/handler.TextRelationExtractionRequest' produces: - application/json responses: @@ -4160,7 +4374,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4194,7 +4408,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.FabriTextRequest' + $ref: '#/definitions/handler.FabriTextRequest' produces: - application/json responses: @@ -4206,7 +4420,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4241,7 +4455,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4270,7 +4484,7 @@ paths: "404": description: 知识库不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4292,7 +4506,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.KBModelConfigRequest' + $ref: '#/definitions/handler.KBModelConfigRequest' produces: - application/json responses: @@ -4304,17 +4518,47 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 知识库不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] summary: 更新知识库配置 tags: - 初始化 + /initialization/models/asr/check: + post: + consumes: + - application/json + description: 检查ASR(语音识别)模型连接是否正常,通过发送一段静默音频测试 /v1/audio/transcriptions 端点 + parameters: + - description: ASR检查请求 + in: body + name: request + required: true + schema: + type: object + produces: + - application/json + responses: + "200": + description: 检查结果 + schema: + additionalProperties: true + type: object + "400": + description: 请求参数错误 + schema: + $ref: '#/definitions/errors.AppError' + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: 检查ASR模型 + tags: + - 初始化 /initialization/models/embedding/test: post: consumes: @@ -4338,7 +4582,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4356,7 +4600,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.RemoteModelCheckRequest' + $ref: '#/definitions/handler.RemoteModelCheckRequest' produces: - application/json responses: @@ -4368,7 +4612,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4398,7 +4642,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4450,7 +4694,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4479,7 +4723,7 @@ paths: "404": description: 任务不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4521,7 +4765,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4556,7 +4800,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4589,7 +4833,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4633,7 +4877,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4650,7 +4894,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeBase' + $ref: '#/definitions/types.KnowledgeBase' produces: - application/json responses: @@ -4662,7 +4906,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4691,7 +4935,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4723,11 +4967,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 知识库不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4749,7 +4993,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.UpdateKnowledgeBaseRequest' + $ref: '#/definitions/handler.UpdateKnowledgeBaseRequest' produces: - application/json responses: @@ -4761,7 +5005,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4801,7 +5045,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4854,7 +5098,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4879,7 +5123,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQBatchUpsertPayload' + $ref: '#/definitions/types.FAQBatchUpsertPayload' produces: - application/json responses: @@ -4891,7 +5135,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4925,11 +5169,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 条目不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4956,7 +5200,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload' + $ref: '#/definitions/types.FAQEntryPayload' produces: - application/json responses: @@ -4968,7 +5212,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -4996,7 +5240,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.addSimilarQuestionsRequest' + $ref: '#/definitions/handler.addSimilarQuestionsRequest' produces: - application/json responses: @@ -5008,11 +5252,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 条目不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5040,7 +5284,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5063,7 +5307,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryFieldsBatchUpdate' + $ref: '#/definitions/types.FAQEntryFieldsBatchUpdate' produces: - application/json responses: @@ -5075,7 +5319,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5110,7 +5354,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5133,7 +5377,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQEntryPayload' + $ref: '#/definitions/types.FAQEntryPayload' produces: - application/json responses: @@ -5145,7 +5389,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5168,7 +5412,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.updateLastFAQImportResultDisplayStatusRequest' + $ref: '#/definitions/handler.updateLastFAQImportResultDisplayStatusRequest' produces: - application/json responses: @@ -5180,11 +5424,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 知识库不存在或无导入记录 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5207,7 +5451,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.FAQSearchRequest' + $ref: '#/definitions/types.FAQSearchRequest' produces: - application/json responses: @@ -5219,7 +5463,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5242,7 +5486,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SearchParams' + $ref: '#/definitions/types.SearchParams' produces: - application/json responses: @@ -5254,7 +5498,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5283,11 +5527,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: 权限不足 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5335,7 +5579,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5381,7 +5625,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "409": description: 文件重复 schema: @@ -5409,7 +5653,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload' + $ref: '#/definitions/types.ManualKnowledgePayload' produces: - application/json responses: @@ -5421,7 +5665,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5469,7 +5713,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "409": description: URL重复 schema: @@ -5503,7 +5747,7 @@ paths: "404": description: 知识库不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5525,7 +5769,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse' + $ref: '#/definitions/types.ListSharesResponse' security: - Bearer: [] summary: 获取知识库的共享列表 @@ -5546,7 +5790,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ShareKnowledgeBaseRequest' + $ref: '#/definitions/types.ShareKnowledgeBaseRequest' produces: - application/json responses: @@ -5613,7 +5857,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateSharePermissionRequest' + $ref: '#/definitions/types.UpdateSharePermissionRequest' produces: - application/json responses: @@ -5665,7 +5909,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5706,7 +5950,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5741,7 +5985,7 @@ paths: in: body name: body schema: - $ref: '#/definitions/internal_handler.DeleteTagRequest' + $ref: '#/definitions/handler.DeleteTagRequest' produces: - application/json responses: @@ -5753,7 +5997,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5792,7 +6036,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5810,7 +6054,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.CopyKnowledgeBaseRequest' + $ref: '#/definitions/handler.CopyKnowledgeBaseRequest' produces: - application/json responses: @@ -5822,7 +6066,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5851,7 +6095,7 @@ paths: "404": description: 任务不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5880,7 +6124,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5908,11 +6152,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 知识不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5934,7 +6178,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Knowledge' + $ref: '#/definitions/types.Knowledge' produces: - application/json responses: @@ -5946,7 +6190,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -5974,7 +6218,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6005,7 +6249,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6034,11 +6278,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "403": description: 权限不足 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6078,7 +6322,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6121,7 +6365,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6144,7 +6388,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ManualKnowledgePayload' + $ref: '#/definitions/types.ManualKnowledgePayload' produces: - application/json responses: @@ -6156,7 +6400,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6201,7 +6445,7 @@ paths: "400": description: Invalid request schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6231,7 +6475,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6254,7 +6498,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6271,7 +6515,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MCPService' + $ref: '#/definitions/types.MCPService' produces: - application/json responses: @@ -6283,7 +6527,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6312,7 +6556,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6340,7 +6584,7 @@ paths: "404": description: 服务不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6374,7 +6618,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6403,7 +6647,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6432,7 +6676,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6461,7 +6705,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6495,7 +6739,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6533,7 +6777,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6570,7 +6814,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.SearchMessagesRequest' + $ref: '#/definitions/handler.SearchMessagesRequest' produces: - application/json responses: @@ -6582,7 +6826,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6605,7 +6849,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6622,7 +6866,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.CreateModelRequest' + $ref: '#/definitions/handler.CreateModelRequest' produces: - application/json responses: @@ -6634,7 +6878,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6663,7 +6907,7 @@ paths: "404": description: 模型不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6691,7 +6935,7 @@ paths: "404": description: 模型不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6713,7 +6957,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler.UpdateModelRequest' + $ref: '#/definitions/handler.UpdateModelRequest' produces: - application/json responses: @@ -6725,7 +6969,7 @@ paths: "404": description: 模型不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -6765,7 +7009,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ListOrganizationsResponse' + $ref: '#/definitions/types.ListOrganizationsResponse' security: - Bearer: [] summary: 获取我的组织列表 @@ -6781,7 +7025,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.CreateOrganizationRequest' + $ref: '#/definitions/types.CreateOrganizationRequest' produces: - application/json responses: @@ -6863,7 +7107,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateOrganizationRequest' + $ref: '#/definitions/types.UpdateOrganizationRequest' produces: - application/json responses: @@ -6897,7 +7141,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.InviteMemberRequest' + $ref: '#/definitions/types.InviteMemberRequest' produces: - application/json responses: @@ -6992,7 +7236,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ReviewJoinRequestRequest' + $ref: '#/definitions/types.ReviewJoinRequestRequest' produces: - application/json responses: @@ -7049,7 +7293,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ListMembersResponse' + $ref: '#/definitions/types.ListMembersResponse' security: - Bearer: [] summary: 获取组织成员列表 @@ -7104,7 +7348,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UpdateMemberRoleRequest' + $ref: '#/definitions/types.UpdateMemberRoleRequest' produces: - application/json responses: @@ -7138,7 +7382,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.RequestRoleUpgradeRequest' + $ref: '#/definitions/types.RequestRoleUpgradeRequest' produces: - application/json responses: @@ -7251,7 +7495,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ListSharesResponse' + $ref: '#/definitions/types.ListSharesResponse' security: - Bearer: [] summary: 获取组织的共享知识库列表 @@ -7268,7 +7512,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.JoinOrganizationRequest' + $ref: '#/definitions/types.JoinOrganizationRequest' produces: - application/json responses: @@ -7297,7 +7541,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.JoinByOrganizationIDRequest' + $ref: '#/definitions/types.JoinByOrganizationIDRequest' produces: - application/json responses: @@ -7326,7 +7570,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SubmitJoinRequestRequest' + $ref: '#/definitions/types.SubmitJoinRequestRequest' produces: - application/json responses: @@ -7421,7 +7665,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7438,7 +7682,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.CreateSessionRequest' + $ref: '#/definitions/handler_session.CreateSessionRequest' produces: - application/json responses: @@ -7450,7 +7694,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7479,7 +7723,7 @@ paths: "404": description: 会话不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7507,7 +7751,7 @@ paths: "404": description: 会话不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7529,7 +7773,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Session' + $ref: '#/definitions/types.Session' produces: - application/json responses: @@ -7541,7 +7785,7 @@ paths: "404": description: 会话不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7570,11 +7814,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 会话不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7597,7 +7841,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.CreateKnowledgeQARequest' + $ref: '#/definitions/handler_session.CreateKnowledgeQARequest' produces: - text/event-stream responses: @@ -7609,7 +7853,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7643,7 +7887,7 @@ paths: "404": description: 会话或消息不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7666,7 +7910,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.CreateKnowledgeQARequest' + $ref: '#/definitions/handler_session.CreateKnowledgeQARequest' produces: - text/event-stream responses: @@ -7678,7 +7922,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7701,7 +7945,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.StopSessionRequest' + $ref: '#/definitions/handler_session.StopSessionRequest' produces: - application/json responses: @@ -7713,7 +7957,7 @@ paths: "404": description: 会话或消息不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7736,7 +7980,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.GenerateTitleRequest' + $ref: '#/definitions/handler_session.GenerateTitleRequest' produces: - application/json responses: @@ -7748,7 +7992,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7766,7 +8010,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.batchDeleteRequest' + $ref: '#/definitions/handler_session.batchDeleteRequest' produces: - application/json responses: @@ -7778,7 +8022,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7796,7 +8040,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/internal_handler_session.SearchKnowledgeRequest' + $ref: '#/definitions/handler_session.SearchKnowledgeRequest' produces: - application/json responses: @@ -7808,7 +8052,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7847,7 +8091,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -7884,35 +8128,10 @@ paths: "200": description: 系统信息 schema: - $ref: '#/definitions/internal_handler.GetSystemInfoResponse' + $ref: '#/definitions/handler.GetSystemInfoResponse' summary: 获取系统信息 tags: - 系统 - /system/minio/buckets: - get: - consumes: - - application/json - description: 获取所有 MinIO 存储桶及其访问权限 - produces: - - application/json - responses: - "200": - description: 存储桶列表 - schema: - $ref: '#/definitions/internal_handler.ListMinioBucketsResponse' - "400": - description: MinIO 未启用 - schema: - additionalProperties: true - type: object - "500": - description: 服务器错误 - schema: - additionalProperties: true - type: object - summary: 列出 MinIO 存储桶 - tags: - - 系统 /system/parser-engines: get: produces: @@ -7956,14 +8175,14 @@ paths: name: body required: true schema: - $ref: '#/definitions/internal_handler.StorageCheckRequest' + $ref: '#/definitions/handler.StorageCheckRequest' produces: - application/json responses: "200": description: OK schema: - $ref: '#/definitions/internal_handler.StorageCheckResponse' + $ref: '#/definitions/handler.StorageCheckResponse' summary: 测试存储引擎连通性 tags: - 系统 @@ -7976,7 +8195,7 @@ paths: "200": description: OK schema: - $ref: '#/definitions/internal_handler.GetStorageEngineStatusResponse' + $ref: '#/definitions/handler.GetStorageEngineStatusResponse' summary: 获取存储引擎状态 tags: - 系统 @@ -7996,7 +8215,7 @@ paths: "500": description: 服务器错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 获取租户列表 @@ -8012,7 +8231,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant' + $ref: '#/definitions/types.Tenant' produces: - application/json responses: @@ -8024,7 +8243,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 创建租户 @@ -8052,7 +8271,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 删除租户 @@ -8079,11 +8298,11 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' "404": description: 租户不存在 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8105,7 +8324,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.Tenant' + $ref: '#/definitions/types.Tenant' produces: - application/json responses: @@ -8117,7 +8336,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 更新租户 @@ -8139,7 +8358,7 @@ paths: "403": description: 权限不足 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] summary: 获取所有租户列表 @@ -8167,7 +8386,7 @@ paths: "400": description: 不支持的键 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8201,7 +8420,7 @@ paths: "400": description: 不支持的键 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8224,7 +8443,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8247,7 +8466,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8270,7 +8489,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8293,7 +8512,7 @@ paths: "400": description: 请求参数错误 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] @@ -8335,32 +8554,276 @@ paths: "403": description: 权限不足 schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + $ref: '#/definitions/errors.AppError' security: - Bearer: [] - ApiKeyAuth: [] summary: 搜索租户 tags: - 租户管理 - /web-search/providers: + /vector-stores: get: - consumes: - - application/json - description: Returns the list of available web search providers from configuration + description: List all vector stores for the current tenant, including environment-configured + and user-created stores produces: - application/json responses: "200": - description: List of providers + description: List of vector stores (env + DB) + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized schema: additionalProperties: true type: object security: - Bearer: [] - ApiKeyAuth: [] - summary: Get available web search providers + summary: List vector stores tags: - - web-search + - VectorStore + post: + consumes: + - application/json + description: Create a new vector store configuration for the current tenant + parameters: + - description: Vector store configuration + in: body + name: request + required: true + schema: + $ref: '#/definitions/handler.CreateStoreRequest' + produces: + - application/json + responses: + "201": + description: Created vector store + schema: + additionalProperties: true + type: object + "400": + description: Invalid request or validation error + schema: + $ref: '#/definitions/errors.AppError' + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "409": + description: Duplicate endpoint and index + schema: + $ref: '#/definitions/errors.AppError' + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Create vector store + tags: + - VectorStore + /vector-stores/{id}: + delete: + description: Soft-delete a vector store. Env stores cannot be deleted. + parameters: + - description: Vector store ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: Deletion success + schema: + additionalProperties: true + type: object + "400": + description: Env store cannot be deleted + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Vector store not found + schema: + additionalProperties: true + type: object + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Delete vector store + tags: + - VectorStore + get: + description: Retrieve a single vector store by ID. Supports both DB stores and + env stores (__env_* IDs) + parameters: + - description: Vector store ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: Vector store details + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Vector store not found + schema: + additionalProperties: true + type: object + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Get vector store + tags: + - VectorStore + put: + consumes: + - application/json + description: Update a vector store (name only). Engine type, connection config, + and index config are immutable. Env stores cannot be modified. + parameters: + - description: Vector store ID + in: path + name: id + required: true + type: string + - description: Updated fields + in: body + name: request + required: true + schema: + $ref: '#/definitions/handler.UpdateStoreRequest' + produces: + - application/json + responses: + "200": + description: Updated vector store + schema: + additionalProperties: true + type: object + "400": + description: Env store or validation error + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Vector store not found + schema: + additionalProperties: true + type: object + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Update vector store + tags: + - VectorStore + /vector-stores/{id}/test: + post: + description: Test connectivity of an existing saved or env store. Returns detected + server version. For DB stores, the version is automatically saved to connection_config. + parameters: + - description: Vector store ID + in: path + name: id + required: true + type: string + produces: + - application/json + responses: + "200": + description: Connection test result (success, version) + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Vector store not found + schema: + additionalProperties: true + type: object + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Test vector store connection by ID + tags: + - VectorStore + /vector-stores/test: + post: + consumes: + - application/json + description: Test connectivity using provided credentials without persisting. + Returns detected server version. + parameters: + - description: Engine type and connection config + in: body + name: request + required: true + schema: + $ref: '#/definitions/handler.TestStoreRequest' + produces: + - application/json + responses: + "200": + description: Connection test result (success, version) + schema: + additionalProperties: true + type: object + "400": + description: Invalid request + schema: + $ref: '#/definitions/errors.AppError' + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Test vector store connection with raw credentials + tags: + - VectorStore + /vector-stores/types: + get: + description: Return supported engine types with connection and index field schemas + for UI form generation + produces: + - application/json + responses: + "200": + description: List of engine types with config schemas + schema: + additionalProperties: true + type: object + summary: List vector store types + tags: + - VectorStore securityDefinitions: ApiKeyAuth: description: 租户身份认证:输入 sk- 开头的 API Key diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 35ad2855..431bcb60 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -109,20 +109,6 @@ export function getPromptTemplates(): Promise<{ data: PromptTemplatesConfig }> { return get('/api/v1/tenants/kv/prompt-templates') } -export interface MinioBucketInfo { - name: string - policy: 'public' | 'private' | 'custom' - created_at?: string -} - -export interface ListMinioBucketsResponse { - buckets: MinioBucketInfo[] -} - -export function listMinioBuckets(): Promise<{ data: ListMinioBucketsResponse }> { - return get('/api/v1/system/minio/buckets') -} - export interface ParserEngineInfo { Name: string Description: string diff --git a/frontend/src/views/settings/ParserEngineSettings.vue b/frontend/src/views/settings/ParserEngineSettings.vue index 535161ee..efa579bc 100644 --- a/frontend/src/views/settings/ParserEngineSettings.vue +++ b/frontend/src/views/settings/ParserEngineSettings.vue @@ -25,195 +25,201 @@

{{ $t('settings.parser.noEngineDetected') }}

- - - -
- - {{ $t('settings.parser.checkWithParams') }} - - {{ $t('settings.parser.saveConfig') }} - {{ checkMessage }} - - {{ saveMessage }} -
+ + + +
+ + + +
+
+ {{ $t('settings.parser.connected') }} + {{ $t('settings.parser.disconnected') }} + {{ docreaderTransport === 'http' ? 'HTTP' : 'gRPC' }} + {{ $t('settings.parser.currentAddr') }}: {{ docreaderAddrEnv }} +
+

+ {{ $t('settings.parser.envVarHint') }} +

+
+ + + + +
+ {{ ft }} +
+ + +
+
+ + +
+
+ + + + + + + + +
+
+ {{ $t('settings.parser.formulaRecognition') }} + {{ $t('settings.parser.tableRecognition') }} + OCR +
+
+ + +
+
+ + +
+
+ + +
+
+ + + + + + +
+
+ {{ $t('settings.parser.formulaRecognition') }} + {{ $t('settings.parser.tableRecognition') }} + OCR +
+
+ + +
+
+
+ +
+ + {{ $t('settings.parser.testConnection', '测试连接') }} + + + {{ checkMessage || saveMessage }} + +
+
+
+ + + @@ -278,6 +284,12 @@ const checkMessage = ref('') const hasBuiltinEngine = computed(() => engines.value.some(e => e.Name === 'builtin')) +const drawerVisible = ref(false) +const currentEngine = ref(null) +const drawerTitle = computed(() => { + return currentEngine.value ? getEngineDisplayName(currentEngine.value.Name) : '' +}) + /** 固定展示顺序,未列出的引擎排在末尾按名称排序 */ const ENGINE_ORDER: Record = { builtin: 0, @@ -321,6 +333,13 @@ function getEngineDisplayDesc(engineName: string, fallback: string): string { return translated !== key ? translated : fallback } +function openDrawer(engine: ParserEngineInfo) { + currentEngine.value = engine + drawerVisible.value = true + saveMessage.value = '' + checkMessage.value = '' +} + async function loadEngines() { try { const res = await getParserEngines() @@ -394,13 +413,47 @@ async function onCheck() { } checking.value = true checkMessage.value = '' + saveMessage.value = '' try { const res = await checkParserEngines(buildConfigPayload()) engines.value = res?.data ?? [] - checkMessage.value = t('settings.parser.checkDoneStatusUpdated') + if (res?.connected !== undefined) { + connected.value = res.connected + } + + if (currentEngine.value) { + if (currentEngine.value.Name === 'builtin') { + if (connected.value) { + checkMessage.value = t('settings.parser.checkSuccess', '测试连接成功') + saveSuccess.value = true + } else { + checkMessage.value = t('settings.parser.checkFailed', '测试连接失败') + saveSuccess.value = false + } + } else { + const updatedEngine = engines.value.find(e => e.Name === currentEngine.value!.Name) + if (updatedEngine) { + if (updatedEngine.Available) { + checkMessage.value = t('settings.parser.checkSuccess', '测试连接成功') + saveSuccess.value = true + } else { + checkMessage.value = updatedEngine.UnavailableReason || t('settings.parser.checkFailed', '测试连接失败') + saveSuccess.value = false + } + } else { + checkMessage.value = t('settings.parser.checkFailed', '引擎状态未知') + saveSuccess.value = false + } + } + } else { + checkMessage.value = t('settings.parser.checkDoneStatusUpdated', '检测已完成,状态已更新') + saveSuccess.value = true + } + setTimeout(() => { checkMessage.value = '' }, 3000) } catch (e: any) { - checkMessage.value = e?.message || t('settings.parser.checkFailed') + checkMessage.value = e?.message || t('settings.parser.checkFailed', '测试连接失败') + saveSuccess.value = false } finally { checking.value = false } @@ -413,6 +466,7 @@ async function onSave() { await updateParserEngineConfig(buildConfigPayload()) saveSuccess.value = true saveMessage.value = t('settings.parser.saveSuccess') + drawerVisible.value = false loadEngines() } catch (e: any) { saveSuccess.value = false @@ -500,34 +554,41 @@ onMounted(loadAll) } } -// ---- 引擎条目 ---- -.engine-item { - padding-top: 24px; +// ---- 引擎卡片布局 ---- +.engine-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 16px; margin-top: 24px; - border-top: 1px solid var(--td-component-stroke); +} - &.first { - margin-top: 0; - padding-top: 0; - border-top: none; +.engine-card { + border: 1px solid var(--td-component-stroke); + border-radius: 8px; + padding: 16px; + cursor: pointer; + transition: all 0.2s ease; + background: var(--td-bg-color-container); + display: flex; + flex-direction: column; + + &:hover { + border-color: var(--td-brand-color); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); + } + + &.active { + border-color: var(--td-brand-color); + background: rgba(var(--td-brand-color-5-rgba), 0.05); } } -.engine-item-header { - margin-bottom: 16px; - - p { - font-size: 13px; - color: var(--td-text-color-placeholder); - margin: 6px 0 0 0; - line-height: 1.5; - } -} - -.engine-title-row { +.engine-card-header { display: flex; align-items: center; - gap: 10px; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; h3 { font-size: 15px; @@ -535,30 +596,86 @@ onMounted(loadAll) color: var(--td-text-color-primary); margin: 0; font-family: 'SF Mono', 'Monaco', 'Menlo', monospace; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +.engine-card-desc { + font-size: 13px; + color: var(--td-text-color-secondary); + margin: 0; + line-height: 1.5; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +// ---- 抽屉内容 ---- +.drawer-content { + display: flex; + flex-direction: column; + gap: 20px; +} + +.engine-info-block { + .engine-desc { + font-size: 13px; + color: var(--td-text-color-secondary); + margin: 0 0 8px 0; + line-height: 1.5; + } +} + +// 输入框样式 +:deep(.t-input), +:deep(.t-select) { + width: 100%; + font-size: 13px; + + .t-input__inner, + .t-input__wrap, + input { + font-size: 13px; + border-radius: 6px; + border-color: var(--td-component-stroke); + transition: all 0.15s ease; + } + + &:hover .t-input__inner, + &:hover .t-input__wrap, + &:hover input { + border-color: var(--td-component-stroke); + } + + &.t-is-focused .t-input__inner, + &.t-is-focused .t-input__wrap, + &.t-is-focused input { + border-color: var(--td-brand-color); + box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1); } } .engine-doc-link { - margin-left: auto; - font-size: 12px; + font-size: 13px; color: var(--td-brand-color); text-decoration: none; - white-space: nowrap; &:hover { - opacity: 0.8; + text-decoration: underline; } } // ---- DocReader 连接信息 ---- .docreader-inline { - padding: 10px 14px; + padding: 12px 16px; background: var(--td-bg-color-secondarycontainer); border-radius: 8px; - margin-bottom: 12px; .status-line { - margin-bottom: 6px; + margin-bottom: 8px; } } @@ -567,13 +684,6 @@ onMounted(loadAll) font-size: 12px; color: var(--td-text-color-placeholder); line-height: 1.6; - - code { - padding: 1px 5px; - font-size: 11px; - background: var(--td-bg-color-secondarycontainer); - border-radius: 3px; - } } .status-line { @@ -593,28 +703,35 @@ onMounted(loadAll) display: flex; flex-wrap: wrap; gap: 6px; - margin-bottom: 4px; } // ---- 配置表单 ---- .engine-form { display: flex; flex-direction: column; - gap: 16px; - margin-top: 16px; - padding-top: 16px; - border-top: 1px dashed var(--td-component-stroke); + gap: 0; } -.form-field { - display: flex; - flex-direction: column; - gap: 6px; +.form-item { + margin-bottom: 20px; - label { - font-size: 13px; - font-weight: 500; - color: var(--td-text-color-secondary); + &:last-child { + margin-bottom: 0; + } +} + +.form-label { + display: block; + margin-bottom: 8px; + font-size: 14px; + font-weight: 500; + color: var(--td-text-color-primary); + + &.required::after { + content: '*'; + color: var(--td-error-color); + margin-left: 4px; + font-weight: 600; } } @@ -622,35 +739,7 @@ onMounted(loadAll) display: flex; flex-wrap: wrap; gap: 16px; -} - -// ---- 保存栏(sticky) ---- -.save-bar { - display: flex; - align-items: center; - gap: 12px; - position: sticky; - bottom: 0; - margin-top: 32px; - padding: 16px 0 4px; - background: linear-gradient(to bottom, transparent 0%, var(--td-bg-color-container) 12%); - z-index: 10; -} - -.save-msg { - font-size: 13px; - - &.success { - color: var(--td-success-color); - } - - &.error { - color: var(--td-error-color); - } - - &.hint { - color: var(--td-text-color-secondary); - } + margin-bottom: 20px; } .tag-with-tooltip { @@ -662,11 +751,10 @@ onMounted(loadAll) display: flex; align-items: flex-start; gap: 8px; - padding: 10px 14px; + padding: 12px 16px; border-radius: 6px; font-size: 13px; color: var(--td-text-color-secondary); - margin-bottom: 12px; background: var(--td-bg-color-secondarycontainer); &--ok { @@ -681,4 +769,76 @@ onMounted(loadAll) border-left: 3px solid #f97316; } } + +.api-test-section { + display: flex; + align-items: center; + gap: 12px; + + .test-message { + font-size: 13px; + line-height: 1.5; + flex: 1; + + &.success { + color: var(--td-brand-color-active); + } + + &.error { + color: var(--td-error-color); + } + + &.hint { + color: var(--td-text-color-secondary); + } + } + + :deep(.t-button) { + min-width: 88px; + height: 32px; + font-size: 13px; + border-radius: 6px; + flex-shrink: 0; + } + + .status-icon { + font-size: 16px; + flex-shrink: 0; + + &.available { + color: var(--td-brand-color); + } + + &.unavailable { + color: var(--td-error-color); + } + } +} + +.drawer-footer-actions { + display: flex; + justify-content: flex-end; + gap: 12px; + width: 100%; + + :deep(.t-button) { + min-width: 80px; + height: 36px; + font-weight: 500; + font-size: 14px; + border-radius: 6px; + transition: all 0.15s ease; + + &.t-button--variant-outline { + color: var(--td-text-color-secondary); + border-color: var(--td-component-stroke); + + &:hover { + border-color: var(--td-brand-color); + color: var(--td-brand-color); + background: rgba(7, 192, 95, 0.04); + } + } + } +} diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue index 703c7120..958f7c0a 100644 --- a/frontend/src/views/settings/Settings.vue +++ b/frontend/src/views/settings/Settings.vue @@ -186,45 +186,11 @@ const navItems = computed(() => [ { key: 'general', icon: 'setting', label: t('general.title') }, { key: 'ollama', icon: 'server', label: 'Ollama' }, { key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' }, - { - key: 'models', - icon: 'control-platform', - label: t('settings.modelManagement'), - children: [ - { key: 'chat', label: t('model.llmModel') }, - { key: 'embedding', label: t('model.embeddingModel') }, - { key: 'rerank', label: t('model.rerankModel') }, - { key: 'vllm', label: t('model.vlmModel') } - ] - }, + { key: 'models', icon: 'control-platform', label: t('settings.modelManagement') }, { key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') }, { key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') }, - { - key: 'parser', - icon: 'file-search', - label: t('settings.parserEngine'), - children: [ - { key: 'builtin', label: 'Builtin (DocReader)' }, - { key: 'weknoracloud', label: 'WeKnora Cloud' }, - { key: 'simple', label: 'Simple' }, - { key: 'markitdown', label: 'Markitdown' }, - { key: 'mineru', label: 'MinerU' }, - { key: 'mineru_cloud', label: 'MinerU Cloud' }, - ] - }, - { - key: 'storage', - icon: 'cloud', - label: t('settings.storageEngine'), - children: [ - { key: 'local', label: 'Local' }, - { key: 'minio', label: 'MinIO' }, - { key: 'cos', label: t('settings.storage.cos') }, - { key: 'tos', label: t('settings.storage.tos') }, - { key: 's3', label: 'AWS S3' }, - { key: 'oss', label: t('settings.storage.oss') }, - ] - }, + { key: 'parser', icon: 'file-search', label: t('settings.parserEngine') }, + { key: 'storage', icon: 'cloud', label: t('settings.storageEngine') }, { key: 'mcp', icon: 'tools', label: t('settings.mcpService') }, { key: 'system', icon: 'info-circle', label: t('settings.systemSettings') }, { key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') }, diff --git a/frontend/src/views/settings/StorageEngineSettings.vue b/frontend/src/views/settings/StorageEngineSettings.vue index 694a5f45..ecb18259 100644 --- a/frontend/src/views/settings/StorageEngineSettings.vue +++ b/frontend/src/views/settings/StorageEngineSettings.vue @@ -28,7 +28,12 @@

{{ $t('settings.storage.defaultEngineDesc') }}

- + @@ -36,475 +41,472 @@ + + {{ saveMessage }} +
- -
-
-
-
-

{{ $t('settings.storage.localTitle') }}

- {{ $t('settings.storage.available') }} -
-

{{ $t('settings.storage.localDesc') }}

+
+ +
+
+

{{ $t('settings.storage.localTitle') }}

+ {{ $t('settings.storage.available') }}
+

{{ $t('settings.storage.localDesc') }}

-
-
- - + + +
+
+

MinIO

+ {{ $t('settings.storage.available') }} + {{ $t('settings.storage.needsConfig') }}
+

{{ $t('settings.storage.minioDesc') }}

+
+ + +
+
+

{{ $t('settings.storage.cosTitle') }}

+ {{ $t('settings.storage.configurable') }} +
+

{{ $t('settings.storage.cosDesc') }}

+
+ + +
+
+

{{ $t('settings.storage.tosTitle') }}

+ {{ $t('settings.storage.configurable') }} +
+

{{ $t('settings.storage.tosDesc') }}

+
+ + +
+
+

{{ $t('settings.storage.s3Title') }}

+ {{ $t('settings.storage.configurable') }} +
+

{{ $t('settings.storage.s3Desc') }}

+
+ + +
+
+

{{ $t('settings.storage.ossTitle') }}

+ {{ $t('settings.storage.configurable') }} +
+

{{ $t('settings.storage.ossDesc') }}

+ - -
-
-
-
-

MinIO

- {{ $t('settings.storage.available') }} - {{ $t('settings.storage.needsConfig') }} -
-

{{ $t('settings.storage.minioDesc') }}

-
-
- -
-
- {{ $t('settings.storage.minioDocker') }} - {{ $t('settings.storage.detected') }} - {{ $t('settings.storage.notDetected') }} -
-
- {{ $t('settings.storage.minioRemote') }} -
-
- - -
-
- {{ $t('settings.storage.minioDockerDetected') }} -
-
- {{ $t('settings.storage.minioDockerNotDetected') }} + + +
+ + + + + - -
-
-
-
-

{{ $t('settings.storage.cosTitle') }}

- {{ $t('settings.storage.configurable') }} -
-

+ + + + + + + + + + + +

+ +
+ + {{ $t('settings.storage.testConnection') }} + + + {{ currentCheckState.result.message }} +
-
- - -
-
- - -
-
- - -
-
- - -
-
-
- {{ $t('settings.storage.testConnection') }} - - {{ ossCheckResult.message }} -
- -
- {{ $t('settings.storage.saveConfig') }} - - {{ saveMessage }} - -
- + +
@@ -515,10 +517,8 @@ import { getStorageEngineConfig, updateStorageEngineConfig, getStorageEngineStatus, - listMinioBuckets, checkStorageEngine, type StorageEngineConfig, - type MinioBucketInfo, } from '@/api/system' const { t } = useI18n() @@ -573,8 +573,6 @@ const engineStatus = ref<{ local: boolean; minio: boolean; cos: boolean }>({ cos: true, }) const minioEnvAvailable = ref(false) -const minioBuckets = ref([]) -const loadingBuckets = ref(false) const saving = ref(false) const saveMessage = ref('') const saveSuccess = ref(false) @@ -590,6 +588,33 @@ const s3CheckResult = ref<{ ok: boolean; message: string } | null>(null) const checkingOss = ref(false) const ossCheckResult = ref<{ ok: boolean; message: string } | null>(null) +const drawerVisible = ref(false) +const currentEngine = ref(null) + +const currentCheckState = computed(() => { + switch (currentEngine.value) { + case 'minio': return { loading: checkingMinio.value, result: minioCheckResult.value, onCheck: onCheckMinio } + case 'cos': return { loading: checkingCos.value, result: cosCheckResult.value, onCheck: onCheckCos } + case 'tos': return { loading: checkingTos.value, result: tosCheckResult.value, onCheck: onCheckTos } + case 's3': return { loading: checkingS3.value, result: s3CheckResult.value, onCheck: onCheckS3 } + case 'oss': return { loading: checkingOss.value, result: ossCheckResult.value, onCheck: onCheckOss } + default: return { loading: false, result: null, onCheck: () => {} } + } +}) + +const drawerTitle = computed(() => { + if (!currentEngine.value) return '' + const titles: Record = { + local: t('settings.storage.localTitle'), + minio: 'MinIO', + cos: t('settings.storage.cosTitle'), + tos: t('settings.storage.tosTitle'), + s3: t('settings.storage.s3Title'), + oss: t('settings.storage.ossTitle'), + } + return titles[currentEngine.value] || currentEngine.value +}) + const minioAvailable = computed(() => { if (config.value.minio?.mode === 'remote') { return !!(config.value.minio.endpoint && config.value.minio.access_key_id && config.value.minio.secret_access_key) @@ -597,6 +622,19 @@ const minioAvailable = computed(() => { return minioEnvAvailable.value }) +function openDrawer(engine: string) { + currentEngine.value = engine + drawerVisible.value = true + saveMessage.value = '' + + // Reset check results + minioCheckResult.value = null + cosCheckResult.value = null + tosCheckResult.value = null + s3CheckResult.value = null + ossCheckResult.value = null +} + async function loadConfig() { try { const res = await getStorageEngineConfig() @@ -684,27 +722,11 @@ async function loadStatus() { } } -async function loadMinioBuckets() { - if (!minioEnvAvailable.value || loadingBuckets.value) return - loadingBuckets.value = true - try { - const res = await listMinioBuckets() - if (res?.data?.buckets) { - minioBuckets.value = res.data.buckets - } - } catch { - minioBuckets.value = [] - } finally { - loadingBuckets.value = false - } -} - async function loadAll() { loading.value = true error.value = '' try { await Promise.all([loadConfig(), loadStatus()]) - if (minioEnvAvailable.value) loadMinioBuckets() } catch (e: unknown) { error.value = e instanceof Error ? e.message : t('settings.storage.loadFailed') } finally { @@ -773,6 +795,7 @@ async function onSave() { await loadStatus() saveSuccess.value = true saveMessage.value = t('settings.storage.saveSuccess') + drawerVisible.value = false } catch (e: unknown) { saveSuccess.value = false saveMessage.value = e instanceof Error ? e.message : t('settings.storage.saveFailed') @@ -781,6 +804,10 @@ async function onSave() { } } +async function onSaveDefaultEngine() { + await onSave() +} + async function onCheckMinio() { checkingMinio.value = true minioCheckResult.value = null @@ -788,10 +815,6 @@ async function onCheckMinio() { const payload = buildPayload() const res = await checkStorageEngine({ provider: 'minio', minio: payload.minio }) minioCheckResult.value = res?.data ?? { ok: false, message: t('settings.storage.unknownError') } - // Refresh bucket list if a new bucket was auto-created - if (res?.data?.bucket_created) { - loadMinioBuckets() - } } catch (e: unknown) { minioCheckResult.value = { ok: false, message: e instanceof Error ? e.message : t('settings.storage.requestFailed') } } finally { @@ -942,81 +965,166 @@ onMounted(loadAll) align-items: center; } -.engine-section { - margin-top: 32px; - padding-top: 32px; - border-top: 1px solid var(--td-component-stroke); +// ---- 引擎卡片布局 ---- +.engine-cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 16px; + margin-top: 24px; } -.engine-header { - margin-bottom: 16px; -} +.engine-card { + border: 1px solid var(--td-component-stroke); + border-radius: 8px; + padding: 16px; + cursor: pointer; + transition: all 0.2s ease; + background: var(--td-bg-color-container); + display: flex; + flex-direction: column; -.engine-header-info { - .engine-title-row { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 6px; - - h3 { - font-size: 17px; - font-weight: 600; - color: var(--td-text-color-primary); - margin: 0; - } + &:hover { + border-color: var(--td-brand-color); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); } - p { - font-size: 13px; - color: var(--td-text-color-placeholder); + &.active { + border-color: var(--td-brand-color); + background: rgba(var(--td-brand-color-5-rgba), 0.05); + } +} + +.engine-card-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; + + h3 { + font-size: 15px; + font-weight: 600; + color: var(--td-text-color-primary); margin: 0; + font-family: 'SF Mono', 'Monaco', 'Menlo', monospace; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +.engine-card-desc { + font-size: 13px; + color: var(--td-text-color-secondary); + margin: 0; + line-height: 1.5; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +// ---- 抽屉内容 ---- +.drawer-content { + display: flex; + flex-direction: column; + gap: 20px; +} + +.engine-info-block { + .engine-desc { + font-size: 13px; + color: var(--td-text-color-secondary); + margin: 0 0 8px 0; line-height: 1.5; } } +// 输入框样式 +:deep(.t-input), +:deep(.t-select) { + width: 100%; + font-size: 13px; + + .t-input__inner, + .t-input__wrap, + input { + font-size: 13px; + border-radius: 6px; + border-color: var(--td-component-stroke); + transition: all 0.15s ease; + } + + &:hover .t-input__inner, + &:hover .t-input__wrap, + &:hover input { + border-color: var(--td-component-stroke); + } + + &.t-is-focused .t-input__inner, + &.t-is-focused .t-input__wrap, + &.t-is-focused input { + border-color: var(--td-brand-color); + box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1); + } +} + .engine-link { - color: var(--td-text-color-placeholder); + color: var(--td-brand-color); text-decoration: none; margin-left: 4px; + font-size: 13px; &:hover { - color: var(--td-brand-color); + text-decoration: underline; } } .engine-form { display: flex; flex-direction: column; - gap: 16px; + gap: 0; } -.form-field { - display: flex; - flex-direction: column; - gap: 6px; +.form-item { + margin-bottom: 20px; - label { - font-size: 13px; - font-weight: 500; - color: var(--td-text-color-secondary); + &:last-child { + margin-bottom: 0; } +} - &--inline { - flex-direction: row; - align-items: center; - gap: 12px; +.form-label { + display: block; + margin-bottom: 8px; + font-size: 14px; + font-weight: 500; + color: var(--td-text-color-primary); - label { - flex-shrink: 0; - } + &.required::after { + content: '*'; + color: var(--td-error-color); + margin-left: 4px; + font-weight: 600; + } +} + +.form-item--inline { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 20px; + + .form-label { + margin-bottom: 0; + flex-shrink: 0; } } .mode-selector { display: flex; gap: 8px; - margin-bottom: 16px; + margin-bottom: 20px; } .mode-option { @@ -1069,41 +1177,71 @@ onMounted(loadAll) } } -.test-bar { +.drawer-actions { display: flex; align-items: center; - gap: 12px; margin-top: 16px; padding-top: 16px; - border-top: 1px solid var(--td-component-stroke); + border-top: 1px dashed var(--td-component-stroke); } -.test-msg { - font-size: 13px; - - &.success { - color: var(--td-success-color); - } - - &.created { - color: var(--td-warning-color); - } - - &.error { - color: var(--td-error-color); - } -} - -.save-bar { +.api-test-section { display: flex; align-items: center; gap: 12px; - position: sticky; - bottom: 0; - margin-top: 32px; - padding: 16px 0 4px; - background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, var(--td-bg-color-container) 12%); - z-index: 10; + + .test-message { + font-size: 13px; + line-height: 1.5; + flex: 1; + + &.success { + color: var(--td-brand-color-active); + } + + &.error { + color: var(--td-error-color); + } + + &.created { + color: var(--td-warning-color); + } + } + + :deep(.t-button) { + min-width: 88px; + height: 32px; + font-size: 13px; + border-radius: 6px; + flex-shrink: 0; + } +} + +.drawer-footer-actions { + display: flex; + justify-content: flex-end; + gap: 12px; + width: 100%; + + :deep(.t-button) { + min-width: 80px; + height: 36px; + font-weight: 500; + font-size: 14px; + border-radius: 6px; + transition: all 0.15s ease; + + &.t-button--variant-outline { + color: var(--td-text-color-secondary); + border-color: var(--td-component-stroke); + + &:hover { + border-color: var(--td-brand-color); + color: var(--td-brand-color); + background: rgba(7, 192, 95, 0.04); + } + } + } } .save-msg { diff --git a/internal/handler/system.go b/internal/handler/system.go index 1af6391d..55acee0a 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -2,7 +2,6 @@ package handler import ( "context" - "encoding/json" "fmt" "net" "os" @@ -442,18 +441,6 @@ func (h *SystemHandler) isTOSEnvAvailable() bool { os.Getenv("TOS_BUCKET_NAME") != "" } -// MinioBucketInfo represents bucket information with access policy -type MinioBucketInfo struct { - Name string `json:"name"` - Policy string `json:"policy"` // "public", "private", "custom" - CreatedAt string `json:"created_at,omitempty"` -} - -// ListMinioBucketsResponse defines the response structure for listing buckets -type ListMinioBucketsResponse struct { - Buckets []MinioBucketInfo `json:"buckets"` -} - // StorageEngineStatusItem describes one storage engine's availability and description. type StorageEngineStatusItem struct { Name string `json:"name"` // "local", "minio", "cos", "tos" @@ -494,188 +481,7 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) { }) } -// ListMinioBuckets godoc -// @Summary 列出 MinIO 存储桶 -// @Description 获取所有 MinIO 存储桶及其访问权限 -// @Tags 系统 -// @Accept json -// @Produce json -// @Success 200 {object} ListMinioBucketsResponse "存储桶列表" -// @Failure 400 {object} map[string]interface{} "MinIO 未启用" -// @Failure 500 {object} map[string]interface{} "服务器错误" -// @Router /system/minio/buckets [get] -func (h *SystemHandler) ListMinioBuckets(c *gin.Context) { - ctx := logger.CloneContext(c.Request.Context()) - - endpoint, accessKeyID, secretAccessKey := h.getMinioConfig(c) - if endpoint == "" || accessKeyID == "" || secretAccessKey == "" { - logger.Warn(ctx, "MinIO is not configured") - c.JSON(400, gin.H{ - "code": 400, - "msg": "MinIO is not configured", - "success": false, - }) - return - } - - useSSL := os.Getenv("MINIO_USE_SSL") == "true" - if v, exists := c.Get(types.TenantInfoContextKey.String()); exists { - if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil { - useSSL = tenant.StorageEngineConfig.MinIO.UseSSL - } - } - - // Create MinIO client - minioClient, err := minio.New(endpoint, &minio.Options{ - Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), - Secure: useSSL, - }) - if err != nil { - logger.Error(ctx, "Failed to create MinIO client", "error", err) - c.JSON(500, gin.H{ - "code": 500, - "msg": "Failed to connect to MinIO", - "success": false, - }) - return - } - - // List all buckets - buckets, err := minioClient.ListBuckets(context.Background()) - if err != nil { - logger.Error(ctx, "Failed to list MinIO buckets", "error", err) - c.JSON(500, gin.H{ - "code": 500, - "msg": "Failed to list buckets", - "success": false, - }) - return - } - - // Get policy for each bucket - bucketInfos := make([]MinioBucketInfo, 0, len(buckets)) - for _, bucket := range buckets { - policy := "private" // default: no policy means private - - // Try to get bucket policy - policyStr, err := minioClient.GetBucketPolicy(context.Background(), bucket.Name) - if err == nil && policyStr != "" { - policy = parseBucketPolicy(policyStr) - } - // If err != nil or policyStr is empty, bucket has no policy (private) - - bucketInfos = append(bucketInfos, MinioBucketInfo{ - Name: bucket.Name, - Policy: policy, - CreatedAt: bucket.CreationDate.Format("2006-01-02 15:04:05"), - }) - } - - logger.Info(ctx, "Listed MinIO buckets successfully", "count", len(bucketInfos)) - c.JSON(200, gin.H{ - "code": 0, - "msg": "success", - "success": true, - "data": ListMinioBucketsResponse{Buckets: bucketInfos}, - }) -} - -// BucketPolicy represents the S3 bucket policy structure -type BucketPolicy struct { - Version string `json:"Version"` - Statement []PolicyStatement `json:"Statement"` -} - -// PolicyStatement represents a single statement in the bucket policy -type PolicyStatement struct { - Effect string `json:"Effect"` - Principal interface{} `json:"Principal"` // Can be "*" or {"AWS": [...]} - Action interface{} `json:"Action"` // Can be string or []string - Resource interface{} `json:"Resource"` // Can be string or []string -} - -// parseBucketPolicy parses the policy JSON and determines the access type -func parseBucketPolicy(policyStr string) string { - var policy BucketPolicy - if err := json.Unmarshal([]byte(policyStr), &policy); err != nil { - // If we can't parse the policy, treat it as custom - return "custom" - } - - // Check if any statement grants public read access - hasPublicRead := false - for _, stmt := range policy.Statement { - if stmt.Effect != "Allow" { - continue - } - - // Check if Principal is "*" (public) - if !isPrincipalPublic(stmt.Principal) { - continue - } - - // Check if Action includes s3:GetObject - if !hasGetObjectAction(stmt.Action) { - continue - } - - hasPublicRead = true - break - } - - if hasPublicRead { - return "public" - } - - // Has policy but not public read - return "custom" -} - -// isPrincipalPublic checks if the principal allows public access -func isPrincipalPublic(principal interface{}) bool { - switch p := principal.(type) { - case string: - return p == "*" - case map[string]interface{}: - // Check for {"AWS": "*"} or {"AWS": ["*"]} - if aws, ok := p["AWS"]; ok { - switch a := aws.(type) { - case string: - return a == "*" - case []interface{}: - for _, v := range a { - if s, ok := v.(string); ok && s == "*" { - return true - } - } - } - } - } - return false -} - -// hasGetObjectAction checks if the action includes s3:GetObject -func hasGetObjectAction(action interface{}) bool { - checkAction := func(a string) bool { - a = strings.ToLower(a) - return a == "s3:getobject" || a == "s3:*" || a == "*" - } - - switch act := action.(type) { - case string: - return checkAction(act) - case []interface{}: - for _, v := range act { - if s, ok := v.(string); ok && checkAction(s) { - return true - } - } - } - return false -} - // --- Storage engine helpers --- - // cosFieldPattern validates COS region and bucket name format to prevent URL injection. var cosFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`) diff --git a/internal/router/router.go b/internal/router/router.go index cfa37736..d0673a98 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -448,7 +448,6 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) { systemRoutes.POST("/docreader/reconnect", handler.ReconnectDocReader) systemRoutes.GET("/storage-engine-status", handler.GetStorageEngineStatus) systemRoutes.POST("/storage-engine-check", handler.CheckStorageEngine) - systemRoutes.GET("/minio/buckets", handler.ListMinioBuckets) } } From fdbd981868871b91dcfd5f120ed0051ea41c6def Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 17:32:36 +0800 Subject: [PATCH 011/192] feat(i18n): update connection test messages and labels in multiple languages --- frontend/src/i18n/locales/en-US.ts | 3 ++- frontend/src/i18n/locales/ko-KR.ts | 3 ++- frontend/src/i18n/locales/ru-RU.ts | 3 ++- frontend/src/i18n/locales/zh-CN.ts | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index ca6c83b5..8c95f99f 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -663,12 +663,13 @@ export default { formulaRecognition: 'Formula Recognition', tableRecognition: 'Table Recognition', language: 'Language', - checkWithParams: 'Check with Current Params', + testConnection: 'Test Connection', saveConfig: 'Save Configuration', docs: 'Docs', loadFailed: 'Failed to load parser engine list', ensureDocreaderConnected: 'Please ensure the DocReader service is configured via environment variables and connected', checkDoneStatusUpdated: 'Checked with current parameters. Status above has been updated.', + checkSuccess: 'Test Connection Successful', checkFailed: 'Check failed', saveSuccess: 'Saved successfully', saveFailed: 'Save failed', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 20c57c31..c52cb0b2 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -525,12 +525,13 @@ export default { formulaRecognition: '수식 인식', tableRecognition: '표 인식', language: '언어', - checkWithParams: '현재 파라미터로 검사', + testConnection: '연결 테스트', saveConfig: '설정 저장', docs: '문서', loadFailed: '파서 엔진 목록 로드 실패', ensureDocreaderConnected: 'DocReader 서비스가 환경변수로 구성되고 연결되었는지 확인하세요', checkDoneStatusUpdated: '현재 파라미터로 검사 완료. 위 상태가 업데이트되었습니다.', + checkSuccess: '연결 테스트 성공', checkFailed: '검사 실패', saveSuccess: '저장 성공', saveFailed: '저장 실패', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index ef5aa882..44ae3dd0 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -644,12 +644,13 @@ export default { formulaRecognition: 'Распознавание формул', tableRecognition: 'Распознавание таблиц', language: 'Язык', - checkWithParams: 'Проверить с текущими параметрами', + testConnection: 'Проверить с текущими параметрами', saveConfig: 'Сохранить конфигурацию', docs: 'Документация', loadFailed: 'Не удалось загрузить список парсеров', ensureDocreaderConnected: 'Убедитесь, что сервис DocReader настроен через переменные окружения и подключён', checkDoneStatusUpdated: 'Проверка выполнена. Статус выше обновлён.', + checkSuccess: 'Тест подключения пройден успешно', checkFailed: 'Проверка не пройдена', saveSuccess: 'Сохранено', saveFailed: 'Ошибка сохранения', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index e092bca4..32ea5810 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -522,12 +522,13 @@ export default { formulaRecognition: "公式识别", tableRecognition: "表格识别", language: "语言", - checkWithParams: "使用当前参数检测", + testConnection: "测试连接", saveConfig: "保存配置", docs: "文档", loadFailed: "加载解析引擎列表失败", ensureDocreaderConnected: "请先确保 DocReader 服务已通过环境变量配置并已连接", checkDoneStatusUpdated: "已使用当前填写参数检测,上方状态已更新", + checkSuccess: "测试连接成功", checkFailed: "检测失败", saveSuccess: "保存成功", saveFailed: "保存失败", From 92b6b7507d7455b587c1d5ce47510538d7af1303 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 18:28:34 +0800 Subject: [PATCH 012/192] refactor(chunk): improve parent-child chunk relationship handling in SplitTextParentChild - Updated the SplitTextParentChild function to maintain a newParents slice, ensuring accurate parent indexing when splitting text into child chunks. - This change enhances the integrity of parent-child relationships by correctly associating child chunks with their respective parents, improving overall chunk processing. --- internal/infrastructure/chunker/splitter.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/internal/infrastructure/chunker/splitter.go b/internal/infrastructure/chunker/splitter.go index a634f2c9..d110e22d 100644 --- a/internal/infrastructure/chunker/splitter.go +++ b/internal/infrastructure/chunker/splitter.go @@ -519,10 +519,18 @@ func SplitTextParentChild(text string, parentCfg, childCfg SplitterConfig) Paren return ParentChildResult{} } + var newParents []Chunk var children []ChildChunk childSeq := 0 - for pi, parent := range parents { + for _, parent := range parents { subs := SplitText(parent.Content, childCfg) + + parentIndex := -1 + if len(subs) > 1 || (len(subs) == 1 && subs[0].Content != parent.Content) { + parentIndex = len(newParents) + newParents = append(newParents, parent) + } + for _, sub := range subs { // Adjust offsets: sub positions are relative to parent content, // shift to document-level offsets. @@ -533,12 +541,12 @@ func SplitTextParentChild(text string, parentCfg, childCfg SplitterConfig) Paren sub.End += parent.Start children = append(children, ChildChunk{ Chunk: sub, - ParentIndex: pi, + ParentIndex: parentIndex, }) childSeq++ } } - return ParentChildResult{Parents: parents, Children: children} + return ParentChildResult{Parents: newParents, Children: children} } // ExtractImageRefs extracts markdown image references from text. From dcb7fd05b108c2021dcc66f8502f44b9534d610c Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 18:37:31 +0800 Subject: [PATCH 013/192] Fix compile error in weaviate repository --- .../repository/retriever/weaviate/repository.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/application/repository/retriever/weaviate/repository.go b/internal/application/repository/retriever/weaviate/repository.go index fbdc8e72..d8b477eb 100644 --- a/internal/application/repository/retriever/weaviate/repository.go +++ b/internal/application/repository/retriever/weaviate/repository.go @@ -429,7 +429,7 @@ func (w *weaviateRepository) BatchUpdateChunkTagID(ctx context.Context, chunkTag // Get all collections collections, err := w.ListCollections(ctx) if err != nil { - log.Errorf("[Weaviate] Failed to list collections: %w", err) + log.Errorf("[Weaviate] Failed to list collections: %v", err) return fmt.Errorf("failed to list collections: %w", err) } @@ -566,10 +566,10 @@ func (w *weaviateRepository) VectorRetrieve(ctx context.Context, log.Errorf("[Weaviate] Vector search failed: %v", err) return nil, fmt.Errorf("failed to search: %w", err) } - if len(result.Errors) > 0 { - log.Errorf("[Weaviate] Vector search failed: %v", result.Errors) - return nil, fmt.Errorf("graphql search failed: %w", result.Errors[0].Message) - } + if len(result.Errors) > 0 { + log.Errorf("[Weaviate] Vector search failed: %v", result.Errors) + return nil, fmt.Errorf("graphql search failed: %s", result.Errors[0].Message) + } data, ok := result.Data["Get"].(map[string]interface{}) if !ok || data[collectionName] == nil { @@ -637,7 +637,7 @@ func (w *weaviateRepository) KeywordsRetrieve(ctx context.Context, } if len(result.Errors) > 0 { log.Errorf("[Weaviate] keywords search failed: %v", result.Errors) - return nil, fmt.Errorf("graphql search failed: %w", result.Errors[0].Message) + return nil, fmt.Errorf("graphql search failed: %s", result.Errors[0].Message) } data, ok := result.Data["Get"].(map[string]interface{}) if !ok || data[collectionName] == nil { From 6235a82183ee21d0faedf24d98726345d1c8fe9b Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 18:39:30 +0800 Subject: [PATCH 014/192] Fix logger format string errors in system handler --- internal/handler/system.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/handler/system.go b/internal/handler/system.go index 55acee0a..0abb4653 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -808,7 +808,7 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types // Strip URL scheme before SSRF check — OSS endpoint may include http:// or https:// ssrfEndpoint := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://") if blocked, reason := isBlockedStorageEndpoint(ssrfEndpoint); blocked { - logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection", "endpoint", endpoint) + logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection, endpoint: %s", endpoint) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}}) return } @@ -825,16 +825,16 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types if err != nil { errMsg := err.Error() if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") { - logger.Errorf(ctx, "Storage check: OSS auth failed", "endpoint", endpoint, "bucket", cfg.BucketName) + logger.Errorf(ctx, "Storage check: OSS auth failed, endpoint: %s, bucket: %s", endpoint, cfg.BucketName) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}}) return } if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") { - logger.Errorf(ctx, "Storage check: OSS bucket not found", "bucket", cfg.BucketName) + logger.Errorf(ctx, "Storage check: OSS bucket not found, bucket: %s", cfg.BucketName) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在", cfg.BucketName)}}) return } - logger.Errorf(ctx, "Storage check: OSS connectivity failed", "endpoint", endpoint, "bucket", cfg.BucketName, "error", err) + logger.Errorf(ctx, "Storage check: OSS connectivity failed, endpoint: %s, bucket: %s, error: %v", endpoint, cfg.BucketName, err) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("OSS 连通性检测失败: %s", sanitizeStorageCheckError(err))}}) return } From 53e8e17df46d7076a7120c6a3abbcb4d9dcacfc0 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 22:39:10 +0800 Subject: [PATCH 015/192] feat(logger): implement LLM debug logging functionality - Added a new logger for LLM calls, enabling detailed logging of model interactions, including request and response data. - Introduced configuration options for enabling and specifying the log directory for LLM debug logs. - Implemented cleanup for old log files to manage disk space effectively. - Wrapped existing chat implementations to log calls when debug logging is enabled, enhancing traceability for model interactions. --- .env.example | 4 + internal/application/repository/chunk.go | 23 +- .../chat_pipeline/into_chat_message.go | 130 +++++---- .../service/chat_pipeline/merge.go | 249 +++++++++++------- .../service/chat_pipeline/search.go | 2 + .../service/chat_pipeline/search_entity.go | 6 +- .../application/service/image_multimodal.go | 93 +------ .../service/knowledgebase_search_results.go | 62 ++++- internal/container/container.go | 31 +++ internal/logger/llm_logger.go | 247 +++++++++++++++++ internal/models/chat/chat.go | 7 +- internal/models/chat/llm_debug.go | 214 +++++++++++++++ internal/models/chat/llm_debug_wrapper.go | 77 ++++++ internal/models/chat/remote_api.go | 10 +- internal/models/embedding/embedder.go | 9 + internal/models/embedding/llm_debug.go | 93 +++++++ internal/models/rerank/llm_debug.go | 70 +++++ internal/models/rerank/reranker.go | 9 + internal/models/vlm/llm_debug.go | 63 +++++ internal/models/vlm/vlm.go | 9 + internal/searchutil/imageinfo.go | 156 +++++++++++ internal/types/tag.go | 5 + 22 files changed, 1304 insertions(+), 265 deletions(-) create mode 100644 internal/logger/llm_logger.go create mode 100644 internal/models/chat/llm_debug.go create mode 100644 internal/models/chat/llm_debug_wrapper.go create mode 100644 internal/models/embedding/llm_debug.go create mode 100644 internal/models/rerank/llm_debug.go create mode 100644 internal/models/vlm/llm_debug.go create mode 100644 internal/searchutil/imageinfo.go diff --git a/.env.example b/.env.example index ac3f1449..c6af148b 100644 --- a/.env.example +++ b/.env.example @@ -14,6 +14,10 @@ GIN_MODE=release # 日志级别,可选值:debug, info, warn, error, fatal,默认为debug # LOG_LEVEL=debug +# LLM 调试日志:将每次大模型调用的完整请求和响应写入独立日志文件,便于排查上下文问题 +# 可选值:true(自动放在 LOG_PATH 同目录下 llm_debug.log)、false/空(关闭)、或指定文件路径 +# LLM_DEBUG_LOG=true + # 时区设置,默认为 Asia/Shanghai # 影响系统时间显示和日志时间戳 # 常用值:Asia/Shanghai, Asia/Tokyo, America/New_York, Europe/London, UTC diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go index bc67498e..b791fa3e 100644 --- a/internal/application/repository/chunk.go +++ b/internal/application/repository/chunk.go @@ -29,14 +29,23 @@ func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chun for _, chunk := range chunks { chunk.Content = common.CleanInvalidUTF8(chunk.Content) } - // Pre-assign SeqIDs for SQLite compatibility (autoIncrement on non-PK columns - // doesn't work in SQLite). This is a no-op if all chunks already have SeqIDs. - if err := types.AssignChunkSeqIDs(r.db.WithContext(ctx), chunks); err != nil { - return fmt.Errorf("failed to assign chunk seq_ids: %w", err) + + db := r.db.WithContext(ctx) + + // SQLite doesn't support autoIncrement on non-PK columns, + // so we must pre-assign SeqIDs manually (safe: single connection). + // PostgreSQL / MySQL use DB sequences — skip to avoid duplicate key + // races under concurrent inserts. + if db.Dialector.Name() == "sqlite" { + if err := types.AssignChunkSeqIDs(db, chunks); err != nil { + return fmt.Errorf("failed to assign chunk seq_ids: %w", err) + } } - // Use Select("*") to ensure all fields including zero values (IsEnabled=false, Flags=0) - // are inserted, bypassing GORM's default value behavior for zero values - return r.db.WithContext(ctx).Select("*").CreateInBatches(chunks, 100).Error + + // Select("*") ensures zero-value fields (IsEnabled=false, Flags=0) are + // explicitly inserted, bypassing GORM's default value behavior. + // SeqID=0 is skipped by GORM automatically (autoIncrement tag). + return db.Select("*").CreateInBatches(chunks, 100).Error } // GetChunkByID retrieves a chunk by its ID and tenant ID diff --git a/internal/application/service/chat_pipeline/into_chat_message.go b/internal/application/service/chat_pipeline/into_chat_message.go index 37f1fee7..9139a59c 100644 --- a/internal/application/service/chat_pipeline/into_chat_message.go +++ b/internal/application/service/chat_pipeline/into_chat_message.go @@ -133,37 +133,32 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context, // Build contexts string based on FAQ priority strategy if chatManage.FAQPriorityEnabled && len(faqResults) > 0 { - // Build structured context with FAQ prioritization - contextsBuilder.WriteString("### Source 1: FAQ Knowledge Base\n") - contextsBuilder.WriteString("[High Confidence - Prioritize these results]\n") + contextsBuilder.WriteString("\n") for i, result := range faqResults { passage := getEnrichedPassageForChat(ctx, result) if hasHighConfidenceFAQ && i == 0 { - contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] Exact Match: %s\n", i+1, passage)) + contextsBuilder.WriteString(fmt.Sprintf("%s\n", i+1, passage)) } else { - contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage)) + contextsBuilder.WriteString(fmt.Sprintf("%s\n", i+1, passage)) } } + contextsBuilder.WriteString("\n") if len(docResults) > 0 { - contextsBuilder.WriteString("\n### Source 2: Reference Documents\n") - contextsBuilder.WriteString("[Supplementary - Use only when FAQ cannot answer the question]\n") + contextsBuilder.WriteString("\n") for i, result := range docResults { passage := getEnrichedPassageForChat(ctx, result) - contextsBuilder.WriteString(fmt.Sprintf("[DOC-%d] %s\n", i+1, passage)) + contextsBuilder.WriteString(fmt.Sprintf("%s\n", i+1, passage)) } + contextsBuilder.WriteString("") } } else { - // Original behavior: simple numbered list - passages := make([]string, len(chatManage.MergeResult)) for i, result := range chatManage.MergeResult { - passages[i] = getEnrichedPassageForChat(ctx, result) - } - for i, passage := range passages { + passage := getEnrichedPassageForChat(ctx, result) if i > 0 { - contextsBuilder.WriteString("\n\n") + contextsBuilder.WriteString("\n") } - contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage)) + contextsBuilder.WriteString(fmt.Sprintf("%s", i+1, passage)) } } @@ -279,15 +274,16 @@ func buildDocumentHeader(results []*types.SearchResult) string { } var b strings.Builder - b.WriteString("### Referenced Documents\n") - for i, d := range docs { - // if d.description != "" { - // b.WriteString(fmt.Sprintf("%d. %s — %s\n", i+1, d.title, d.description)) - // } else { - // b.WriteString(fmt.Sprintf("%d. %s\n", i+1, d.title)) - // } - b.WriteString(fmt.Sprintf("%d. %s\n", i+1, d.title)) + b.WriteString("\n") + for _, d := range docs { + b.WriteString("\n") + b.WriteString(fmt.Sprintf("%s\n", d.title)) + if d.description != "" { + b.WriteString(fmt.Sprintf("%s\n", d.description)) + } + b.WriteString("\n") } + b.WriteString("") return b.String() } @@ -310,105 +306,101 @@ func getEnrichedPassageForChat(ctx context.Context, result *types.SearchResult) // 正则表达式用于匹配Markdown图片链接 var markdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`) -// enrichContentWithImageInfo 将图片信息与文本内容合并 +// enrichContentWithImageInfo 将图片信息以 XML 标签的形式嵌入文本内容。 +// 对于内容中已有的 Markdown 图片链接,在其后附加 / ; +// 对于未出现在内容中的图片,以 块追加到末尾。 func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJSON string) string { - // 解析ImageInfo var imageInfos []types.ImageInfo - err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos) - if err != nil { + if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil { pipelineWarn(ctx, "IntoChatMessage", "image_parse_error", map[string]interface{}{ "error": err.Error(), }) return content } - if len(imageInfos) == 0 { return content } - // 创建图片URL到信息的映射 imageInfoMap := make(map[string]*types.ImageInfo) for i := range imageInfos { if imageInfos[i].URL != "" { imageInfoMap[imageInfos[i].URL] = &imageInfos[i] } - // 同时检查原始URL if imageInfos[i].OriginalURL != "" { imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i] } } - // 查找内容中的所有Markdown图片链接 matches := markdownImageRegex.FindAllStringSubmatch(content, -1) - - // 用于存储已处理的图片URL processedURLs := make(map[string]bool) pipelineInfo(ctx, "IntoChatMessage", "image_markdown_links", map[string]interface{}{ "match_count": len(matches), }) - // 替换每个图片链接,添加描述和OCR文本 for _, match := range matches { if len(match) < 3 { continue } - - // 提取图片URL,忽略alt文本 imgURL := match[2] - - // 标记该URL已处理 processedURLs[imgURL] = true - // 查找匹配的图片信息 imgInfo, found := imageInfoMap[imgURL] - - // 如果找到匹配的图片信息,添加描述和OCR文本 + var b strings.Builder + b.WriteString(fmt.Sprintf("\n", imgURL)) + b.WriteString(fmt.Sprintf("%s\n", match[0])) if found && imgInfo != nil { - replacement := match[0] + "\n" - if imgInfo.Caption != "" { - replacement += fmt.Sprintf("Image Caption: %s\n", imgInfo.Caption) - } - if imgInfo.OCRText != "" { - replacement += fmt.Sprintf("Image Text: %s\n", imgInfo.OCRText) - } - content = strings.Replace(content, match[0], replacement, 1) + b.WriteString(buildImageInfoXML(imgInfo)) } + b.WriteString("") + content = strings.Replace(content, match[0], b.String(), 1) } - // 处理未在内容中找到但存在于ImageInfo中的图片 - var additionalImageTexts []string + // Append image info not found as inline Markdown links + var extras []string for _, imgInfo := range imageInfos { - // 如果图片URL已经处理过,跳过 if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] { continue } - - var imgTexts []string - if imgInfo.Caption != "" { - imgTexts = append(imgTexts, fmt.Sprintf("Image %s caption: %s", imgInfo.URL, imgInfo.Caption)) + url := imgInfo.URL + if url == "" { + url = imgInfo.OriginalURL } - if imgInfo.OCRText != "" { - imgTexts = append(imgTexts, fmt.Sprintf("Image %s text: %s", imgInfo.URL, imgInfo.OCRText)) - } - - if len(imgTexts) > 0 { - additionalImageTexts = append(additionalImageTexts, imgTexts...) + if block := buildImageInfoXMLWithURL(url, &imgInfo); block != "" { + extras = append(extras, block) } } - - // 如果有额外的图片信息,添加到内容末尾 - if len(additionalImageTexts) > 0 { + if len(extras) > 0 { if content != "" { - content += "\n\n" + content += "\n" } - content += "Additional Image Info:\n" + strings.Join(additionalImageTexts, "\n") + content += strings.Join(extras, "\n") } pipelineInfo(ctx, "IntoChatMessage", "image_enrich_summary", map[string]interface{}{ "markdown_images": len(matches), - "additional_imgs": len(additionalImageTexts), + "additional_imgs": len(extras), }) - return content } + +// buildImageInfoXML returns XML-tagged caption / ocr for one image. +func buildImageInfoXML(img *types.ImageInfo) string { + var b strings.Builder + if img.Caption != "" { + b.WriteString(fmt.Sprintf("%s\n", img.Caption)) + } + if img.OCRText != "" { + b.WriteString(fmt.Sprintf("%s\n", img.OCRText)) + } + return b.String() +} + +// buildImageInfoXMLWithURL wraps image info in an element carrying the URL. +func buildImageInfoXMLWithURL(url string, img *types.ImageInfo) string { + inner := buildImageInfoXML(img) + if inner == "" { + return "" + } + return fmt.Sprintf("\n%s", url, inner) +} diff --git a/internal/application/service/chat_pipeline/merge.go b/internal/application/service/chat_pipeline/merge.go index c5b732cb..ae199da5 100644 --- a/internal/application/service/chat_pipeline/merge.go +++ b/internal/application/service/chat_pipeline/merge.go @@ -260,136 +260,207 @@ func (p *PluginMerge) resolveParentChunks( parentMap[c.ID] = c } + // Check if any results are image chunks; only then do we need + // grandparent resolution and the extra DB round-trip. + hasImageResults := false + for _, r := range results { + if r.ChunkType == string(types.ChunkTypeImageOCR) || r.ChunkType == string(types.ChunkTypeImageCaption) { + hasImageResults = true + break + } + } + + var grandparentIDs []string + if hasImageResults { + // Fetch grandparent chunks for the image → text → parent_text chain. + for _, pc := range parentChunks { + if pc.ParentChunkID != "" && pc.ChunkType == types.ChunkTypeText { + if _, already := parentMap[pc.ParentChunkID]; !already { + grandparentIDs = append(grandparentIDs, pc.ParentChunkID) + } + } + } + if len(grandparentIDs) > 0 { + gpChunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, grandparentIDs) + if err != nil { + pipelineWarn(ctx, "Merge", "grandparent_fetch_failed", map[string]interface{}{ + "error": err.Error(), + }) + } else { + for _, c := range gpChunks { + parentMap[c.ID] = c + } + } + } + } + // Collect merged ImageInfo for each parent by fetching ALL sibling // child chunks. Individual child chunks only carry ImageInfo for images // within their own range, but the parent content spans all children. - parentImageInfoMap := p.collectParentImageInfo(ctx, tenantID, ids) + imageInfoIDs := ids + if len(grandparentIDs) > 0 { + imageInfoIDs = append(append([]string(nil), ids...), grandparentIDs...) + } + parentImageInfoMap := p.collectParentImageInfo(ctx, tenantID, imageInfoIDs) - // Replace child content with parent content. - // Only replace for text chunks whose parent is a parent_text chunk - // (i.e., the parent-child chunking strategy). Summary chunks also carry - // a ParentChunkID that points to their source chunk, but that is a - // different semantic — replacing summary content with its source would - // degrade quality. for _, r := range results { if r.ParentChunkID == "" { continue } - // Skip non-text chunks (e.g., summary, image_caption) — their - // ParentChunkID has a different meaning than the parent-child - // chunking strategy. - if r.ChunkType != string(types.ChunkTypeText) { - continue - } - parent, ok := parentMap[r.ParentChunkID] - if !ok || parent.Content == "" { - continue - } - // Only replace if the parent is actually a parent_text chunk from - // the parent-child chunking strategy. - if parent.ChunkType != types.ChunkTypeParentText { - continue - } - pipelineInfo(ctx, "Merge", "parent_resolve", map[string]interface{}{ - "child_id": r.ID, - "parent_id": r.ParentChunkID, - "child_len": runeLen(r.Content), - "parent_len": runeLen(parent.Content), - }) - r.Content = parent.Content - r.StartAt = parent.StartAt - r.EndAt = parent.EndAt - if mergedImageInfo, ok := parentImageInfoMap[r.ParentChunkID]; ok && mergedImageInfo != "" { - r.ImageInfo = mergedImageInfo - } - // Track the original child as a sub-chunk - if !containsID(r.SubChunkID, r.ID) { - r.SubChunkID = append(r.SubChunkID, r.ID) + + switch r.ChunkType { + case string(types.ChunkTypeText): + // text → parent_text resolution (parent-child chunking strategy). + // Summary chunks also carry a ParentChunkID that points to their + // source chunk, but that is a different semantic — replacing + // summary content with its source would degrade quality. + parent, ok := parentMap[r.ParentChunkID] + if !ok || parent.Content == "" || parent.ChunkType != types.ChunkTypeParentText { + continue + } + pipelineInfo(ctx, "Merge", "parent_resolve", map[string]interface{}{ + "child_id": r.ID, + "parent_id": r.ParentChunkID, + "child_len": runeLen(r.Content), + "parent_len": runeLen(parent.Content), + }) + r.Content = parent.Content + r.StartAt = parent.StartAt + r.EndAt = parent.EndAt + if mergedImageInfo, ok := parentImageInfoMap[r.ParentChunkID]; ok && mergedImageInfo != "" { + r.ImageInfo = mergedImageInfo + } + if !containsID(r.SubChunkID, r.ID) { + r.SubChunkID = append(r.SubChunkID, r.ID) + } + + case string(types.ChunkTypeImageOCR), string(types.ChunkTypeImageCaption): + // image_ocr/image_caption → text parent → optional parent_text grandparent. + // Replace content with parent text for surrounding context. + parent, ok := parentMap[r.ParentChunkID] + if !ok || parent.Content == "" { + continue + } + resolvedParent := parent + // If parent text uses parent-child chunking, resolve one more level + if parent.ChunkType == types.ChunkTypeText && parent.ParentChunkID != "" { + if gp, gpOK := parentMap[parent.ParentChunkID]; gpOK && gp.ChunkType == types.ChunkTypeParentText && gp.Content != "" { + resolvedParent = gp + } + } + pipelineInfo(ctx, "Merge", "image_parent_resolve", map[string]interface{}{ + "child_id": r.ID, + "child_type": r.ChunkType, + "resolved_id": resolvedParent.ID, + "child_len": runeLen(r.Content), + "parent_len": runeLen(resolvedParent.Content), + }) + r.Content = resolvedParent.Content + r.StartAt = resolvedParent.StartAt + r.EndAt = resolvedParent.EndAt + if mergedInfo, ok := parentImageInfoMap[resolvedParent.ID]; ok && mergedInfo != "" { + r.ImageInfo = mergedInfo + } + if !containsID(r.SubChunkID, r.ID) { + r.SubChunkID = append(r.SubChunkID, r.ID) + } } } return results } -// collectParentImageInfo batch-fetches all child chunks for the given parents -// and merges their ImageInfo into a single JSON string per parent. This ensures -// that when child content is replaced with parent content, the complete set of -// image descriptions across all sibling chunks is preserved. +// collectParentImageInfo batch-fetches image info for the given parent_text +// chunk IDs using a two-level query: +// +// Level 1: parent_text → text children +// Level 2: text children → image_ocr / image_caption grandchildren (carry image_info) func (p *PluginMerge) collectParentImageInfo( ctx context.Context, tenantID uint64, parentIDs []string, ) map[string]string { - result := make(map[string]string, len(parentIDs)) - - allChildren, err := p.chunkRepo.ListChunksByParentIDs(ctx, tenantID, parentIDs) + // Level 1: get direct children of parent_text chunks + children, err := p.chunkRepo.ListChunksByParentIDs(ctx, tenantID, parentIDs) if err != nil { pipelineWarn(ctx, "Merge", "parent_imageinfo_fetch_failed", map[string]interface{}{ "parent_cnt": len(parentIDs), "error": err.Error(), }) - return result + return nil } - // Group children by parent chunk ID, collecting unique ImageInfo entries - type parentAgg struct { - imageInfos []types.ImageInfo - uniqueURLs map[string]bool - siblingCnt int + type agg struct { + infos []types.ImageInfo + seenURLs map[string]bool } - aggMap := make(map[string]*parentAgg, len(parentIDs)) - - for _, child := range allChildren { - agg, ok := aggMap[child.ParentChunkID] - if !ok { - agg = &parentAgg{uniqueURLs: make(map[string]bool)} - aggMap[child.ParentChunkID] = agg - } - agg.siblingCnt++ - - if child.ImageInfo == "" { - continue + aggMap := make(map[string]*agg) + addInfo := func(targetID string, chunk *types.Chunk) { + if chunk.ImageInfo == "" { + return } var infos []types.ImageInfo - if err := json.Unmarshal([]byte(child.ImageInfo), &infos); err != nil { - pipelineWarn(ctx, "Merge", "parent_imageinfo_parse", map[string]interface{}{ - "chunk_id": child.ID, - "error": err.Error(), - }) - continue + if err := json.Unmarshal([]byte(chunk.ImageInfo), &infos); err != nil || len(infos) == 0 { + return + } + a, ok := aggMap[targetID] + if !ok { + a = &agg{seenURLs: make(map[string]bool)} + aggMap[targetID] = a } for _, info := range infos { key := info.URL if key == "" { key = info.OriginalURL } - if key != "" && !agg.uniqueURLs[key] { - agg.uniqueURLs[key] = true - agg.imageInfos = append(agg.imageInfos, info) + if key != "" && !a.seenURLs[key] { + a.seenURLs[key] = true + a.infos = append(a.infos, info) } } } - for parentID, agg := range aggMap { - if len(agg.imageInfos) == 0 { - continue + var textChildIDs []string + textToParent := make(map[string]string, len(children)) + for _, child := range children { + switch child.ChunkType { + case types.ChunkTypeImageOCR, types.ChunkTypeImageCaption: + addInfo(child.ParentChunkID, child) + case types.ChunkTypeText: + textChildIDs = append(textChildIDs, child.ID) + textToParent[child.ID] = child.ParentChunkID } - merged, err := json.Marshal(agg.imageInfos) - if err != nil { - pipelineWarn(ctx, "Merge", "parent_imageinfo_marshal", map[string]interface{}{ - "parent_id": parentID, - "error": err.Error(), - }) - continue - } - result[parentID] = string(merged) - - pipelineInfo(ctx, "Merge", "parent_imageinfo_collected", map[string]interface{}{ - "parent_id": parentID, - "sibling_cnt": agg.siblingCnt, - "image_cnt": len(agg.imageInfos), - }) } + // Level 2: text children → image grandchildren + if len(textChildIDs) > 0 { + grandChildren, err := p.chunkRepo.ListChunksByParentIDs(ctx, tenantID, textChildIDs) + if err != nil { + pipelineWarn(ctx, "Merge", "parent_imageinfo_l2_fetch_failed", map[string]interface{}{ + "text_cnt": len(textChildIDs), + "error": err.Error(), + }) + } else { + for _, gc := range grandChildren { + if gc.ChunkType != types.ChunkTypeImageOCR && gc.ChunkType != types.ChunkTypeImageCaption { + continue + } + if parentTextID, ok := textToParent[gc.ParentChunkID]; ok { + addInfo(parentTextID, gc) + } + } + } + } + + result := make(map[string]string, len(aggMap)) + for id, a := range aggMap { + if len(a.infos) == 0 { + continue + } + data, err := json.Marshal(a.infos) + if err == nil { + result[id] = string(data) + } + } return result } diff --git a/internal/application/service/chat_pipeline/search.go b/internal/application/service/chat_pipeline/search.go index 003e08c5..947a2aa6 100644 --- a/internal/application/service/chat_pipeline/search.go +++ b/internal/application/service/chat_pipeline/search.go @@ -611,6 +611,8 @@ func (p *PluginSearch) tryDirectChunkLoading(ctx context.Context, tenantID uint6 results = append(results, res) } + searchutil.EnrichSearchResultsImageInfo(ctx, p.chunkService.GetRepository(), tenantID, results) + return results, skippedIDs } diff --git a/internal/application/service/chat_pipeline/search_entity.go b/internal/application/service/chat_pipeline/search_entity.go index 23db34a6..90415e3a 100644 --- a/internal/application/service/chat_pipeline/search_entity.go +++ b/internal/application/service/chat_pipeline/search_entity.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" ) @@ -161,10 +162,13 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context, for _, knowledge := range knowledges { knowledgeMap[knowledge.ID] = knowledge } + var entityResults []*types.SearchResult for _, chunk := range chunks { searchResult := chunk2SearchResult(chunk, knowledgeMap[chunk.KnowledgeID]) - chatManage.SearchResult = append(chatManage.SearchResult, searchResult) + entityResults = append(entityResults, searchResult) } + searchutil.EnrichSearchResultsImageInfo(ctx, p.chunkRepo, types.MustTenantIDFromContext(ctx), entityResults) + chatManage.SearchResult = append(chatManage.SearchResult, entityResults...) // remove duplicate results chatManage.SearchResult = removeDuplicateResults(chatManage.SearchResult) if len(chatManage.SearchResult) == 0 { diff --git a/internal/application/service/image_multimodal.go b/internal/application/service/image_multimodal.go index b0e810b8..0d1c83d7 100644 --- a/internal/application/service/image_multimodal.go +++ b/internal/application/service/image_multimodal.go @@ -172,13 +172,11 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e } } - if payload.EnableCaption { - caption, capErr := vlmModel.Predict(ctx, [][]byte{imgBytes}, vlmCaptionPrompt) - if capErr != nil { - logger.Warnf(ctx, "[ImageMultimodal] Caption failed for %s: %v", payload.ImageURL, capErr) - } else if caption != "" { - imageInfo.Caption = caption - } + caption, capErr := vlmModel.Predict(ctx, [][]byte{imgBytes}, vlmCaptionPrompt) + if capErr != nil { + logger.Warnf(ctx, "[ImageMultimodal] Caption failed for %s: %v", payload.ImageURL, capErr) + } else if caption != "" { + imageInfo.Caption = caption } // Build child chunks for OCR and caption results @@ -220,8 +218,6 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e } if len(newChunks) == 0 { - // Even if OCR/caption both failed, mark knowledge as completed - s.finalizeImageKnowledge(ctx, payload, "") s.checkAndFinalizeAllImages(ctx, payload) return nil } @@ -238,13 +234,6 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e // Index chunks so they can be retrieved s.indexChunks(ctx, payload, newChunks) - // Update the parent text chunk's ImageInfo (mirrors old docreader behaviour) - s.updateParentChunkImageInfo(ctx, payload, imageInfo) - - // For standalone image files, use caption as the knowledge description - // and mark the knowledge as completed (it was kept in "processing" until now). - s.finalizeImageKnowledge(ctx, payload, imageInfo.Caption) - // Enqueue question generation for the caption/OCR content if KB has it enabled. // During initial processChunks, question generation is skipped for image-type // knowledge because the text chunk is just a markdown reference. Now that we @@ -256,36 +245,6 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e return nil } -// finalizeImageKnowledge updates the knowledge after multimodal processing: -// - For standalone image files: sets Description from caption and marks ParseStatus as completed -// (processChunks kept it in "processing" to wait for multimodal results). -// - For images extracted from PDFs: no-op (description comes from summary generation). -func (s *ImageMultimodalService) finalizeImageKnowledge(ctx context.Context, payload types.ImageMultimodalPayload, caption string) { - knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID) - if err != nil { - logger.Warnf(ctx, "[ImageMultimodal] Failed to get knowledge %s: %v", payload.KnowledgeID, err) - return - } - if knowledge == nil { - return - } - if !IsImageType(knowledge.FileType) { - return - } - - if caption != "" { - knowledge.Description = caption - } - knowledge.ParseStatus = types.ParseStatusCompleted - knowledge.UpdatedAt = time.Now() - if err := s.knowledgeRepo.UpdateKnowledge(ctx, knowledge); err != nil { - logger.Warnf(ctx, "[ImageMultimodal] Failed to finalize knowledge: %v", err) - } else { - logger.Infof(ctx, "[ImageMultimodal] Finalized image knowledge %s (status=completed, description=%d chars)", - payload.KnowledgeID, len(knowledge.Description)) - } -} - // indexChunks indexes the newly created multimodal chunks into the retrieval engine // so they can participate in semantic search. func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types.ImageMultimodalPayload, chunks []*types.Chunk) { @@ -348,47 +307,6 @@ func (s *ImageMultimodalService) indexChunks(ctx context.Context, payload types. logger.Infof(ctx, "[ImageMultimodal] Indexed %d multimodal chunks for image %s", len(chunks), payload.ImageURL) } -// updateParentChunkImageInfo updates the parent text chunk's ImageInfo field, -// replicating the behaviour of the old docreader flow where the parent chunk -// carried the full image metadata (URL, OCR, caption). -func (s *ImageMultimodalService) updateParentChunkImageInfo(ctx context.Context, payload types.ImageMultimodalPayload, imageInfo types.ImageInfo) { - if payload.ChunkID == "" { - return - } - - chunk, err := s.chunkService.GetChunkByIDOnly(ctx, payload.ChunkID) - if err != nil { - logger.Warnf(ctx, "[ImageMultimodal] Failed to get parent chunk %s: %v", payload.ChunkID, err) - return - } - - var existingInfos []types.ImageInfo - if chunk.ImageInfo != "" { - _ = json.Unmarshal([]byte(chunk.ImageInfo), &existingInfos) - } - - found := false - for i, info := range existingInfos { - if info.URL == imageInfo.URL { - existingInfos[i] = imageInfo - found = true - break - } - } - if !found { - existingInfos = append(existingInfos, imageInfo) - } - - imageInfoJSON, _ := json.Marshal(existingInfos) - chunk.ImageInfo = string(imageInfoJSON) - chunk.UpdatedAt = time.Now() - if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil { - logger.Warnf(ctx, "[ImageMultimodal] Failed to update parent chunk %s ImageInfo: %v", chunk.ID, err) - } else { - logger.Infof(ctx, "[ImageMultimodal] Updated parent chunk %s ImageInfo for image %s", chunk.ID, payload.ImageURL) - } -} - // resolveVLM creates a vlm.VLM instance for the given knowledge base, // supporting both new-style (ModelID) and legacy (inline BaseURL) configs. func (s *ImageMultimodalService) resolveVLM(ctx context.Context, kbID string) (vlm.VLM, error) { @@ -464,7 +382,6 @@ func (s *ImageMultimodalService) checkAndFinalizeAllImages(ctx context.Context, logger.Infof(ctx, "[ImageMultimodal] All images processed for knowledge %s. Finalizing...", payload.KnowledgeID) s.redisClient.Del(ctx, redisKey) - // Enqueue the post process task to handle all downstream tasks (summary, question generation, etc) s.enqueueKnowledgePostProcessTask(ctx, payload) } } diff --git a/internal/application/service/knowledgebase_search_results.go b/internal/application/service/knowledgebase_search_results.go index 2922fc37..7b8b56cc 100644 --- a/internal/application/service/knowledgebase_search_results.go +++ b/internal/application/service/knowledgebase_search_results.go @@ -6,6 +6,7 @@ import ( "slices" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" ) @@ -59,12 +60,32 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context, for _, chunk := range additionalChunks { chunkMap[chunk.ID] = chunk } + // Second round: only needed when image chunks are among primary + // results (image → text resolved above, now text → parent_text). + // For normal text-only results this is a no-op. + if s.hasImageChunks(allChunks) { + parentIDs := s.collectParentChunkIDs(additionalChunks, index) + if len(parentIDs) > 0 { + logger.Infof(ctx, "Fetching %d second-level parent chunks", len(parentIDs)) + parentChunks, err := s.listChunksByIDWithShared(ctx, tenantID, parentIDs) + if err != nil { + logger.Warnf(ctx, "Failed to fetch second-level parent chunks: %v", err) + } else { + for _, chunk := range parentChunks { + chunkMap[chunk.ID] = chunk + } + } + } + } } } } // Build final search results searchResults := s.assembleSearchResults(ctx, chunks, chunkMap, knowledgeMap, index, skipEnrichment) + + searchutil.EnrichSearchResultsImageInfo(ctx, s.chunkRepo, tenantID, searchResults) + logger.Infof(ctx, "Search results processed, total: %d", len(searchResults)) return searchResults, nil } @@ -151,6 +172,36 @@ func (s *knowledgeBaseService) collectEnrichmentChunkIDs( return additionalIDs } +// collectParentChunkIDs returns unprocessed parent IDs from the given chunks. +// Unlike collectEnrichmentChunkIDs, this only resolves parent links without +// expanding nearby or related chunks, making it suitable for second-round +// parent chain resolution (e.g., text → parent_text after image → text). +func (s *knowledgeBaseService) collectParentChunkIDs( + chunks []*types.Chunk, + idx *chunkIndex, +) []string { + var ids []string + for _, chunk := range chunks { + if chunk.ParentChunkID != "" && !idx.processedIDs[chunk.ParentChunkID] { + ids = append(ids, chunk.ParentChunkID) + idx.processedIDs[chunk.ParentChunkID] = true + idx.scores[chunk.ParentChunkID] = idx.scores[chunk.ID] + idx.matchTypes[chunk.ParentChunkID] = types.MatchTypeParentChunk + } + } + return ids +} + +// hasImageChunks returns true if any chunk is an image_ocr or image_caption type. +func (s *knowledgeBaseService) hasImageChunks(chunks []*types.Chunk) bool { + for _, c := range chunks { + if c.ChunkType == types.ChunkTypeImageOCR || c.ChunkType == types.ChunkTypeImageCaption { + return true + } + } + return false +} + // assembleSearchResults builds the final []*types.SearchResult from chunk data and knowledge data. // Primary results (from input chunks) are added first in order, then enrichment results. func (s *knowledgeBaseService) assembleSearchResults( @@ -174,7 +225,7 @@ func (s *knowledgeBaseService) assembleSearchResults( logger.Debugf(ctx, "Chunk not found in chunkMap: %s", inputChunk.ChunkID) continue } - if !s.isValidTextChunk(chunk) { + if !s.isSearchableChunk(chunk) { invalidChunkCnt++ if len(invalidChunkSamples) < maxInvalidChunkLog { invalidChunkSamples = append(invalidChunkSamples, chunk.ID+":"+chunk.ChunkType) @@ -197,7 +248,7 @@ func (s *knowledgeBaseService) assembleSearchResults( } if invalidChunkCnt > 0 { logger.Debugf(ctx, - "Skip non-text chunks in search results: total=%d sampled=%d samples=%v", + "Skip non-searchable chunks in search results: total=%d sampled=%d samples=%v", invalidChunkCnt, len(invalidChunkSamples), invalidChunkSamples, ) } @@ -205,7 +256,7 @@ func (s *knowledgeBaseService) assembleSearchResults( // Second pass: Add enrichment chunks (parent, nearby, relation) if !skipEnrichment { for chunkID, chunk := range chunkMap { - if addedChunkIDs[chunkID] || !s.isValidTextChunk(chunk) { + if addedChunkIDs[chunkID] || !s.isSearchableChunk(chunk) { continue } @@ -280,11 +331,12 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk, } } -// isValidTextChunk checks if a chunk is a valid text chunk. -func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool { +// isSearchableChunk checks if a chunk type should be included in search results. +func (s *knowledgeBaseService) isSearchableChunk(chunk *types.Chunk) bool { return slices.Contains([]types.ChunkType{ types.ChunkTypeText, types.ChunkTypeSummary, types.ChunkTypeTableColumn, types.ChunkTypeTableSummary, types.ChunkTypeFAQ, + types.ChunkTypeImageOCR, types.ChunkTypeImageCaption, }, chunk.ChunkType) } diff --git a/internal/container/container.go b/internal/container/container.go index 886c819b..7b75a6d4 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -516,10 +516,41 @@ func resolveStorageProviderPending(db *gorm.DB) { logger.Infof(context.Background(), "Resolved %d knowledge bases with __pending_env__ storage provider → %s", result.RowsAffected, storageType) } + // Sync PostgreSQL sequences with actual MAX values to prevent duplicate key + // errors. The old code assigned seq_id via SELECT MAX()+1 in application + // code, which could push values past the DB sequence counter. + syncSequences(db) + // Reset any pending tasks left over from previous aborted runs (Lite App mode) resetPendingTasks(db) } +// syncSequences ensures PostgreSQL sequences for auto-increment columns (seq_id) +// are at least as high as the current MAX value in each table. This is needed +// because older code assigned seq_id via application-level MAX()+1, which could +// advance values past the DB sequence counter and cause duplicate key errors. +func syncSequences(db *gorm.DB) { + if db.Dialector.Name() != "postgres" { + return + } + pairs := [][2]string{ + {"chunks", "chunks_seq_id_seq"}, + {"knowledge_tags", "knowledge_tags_seq_id_seq"}, + } + for _, p := range pairs { + table, seq := p[0], p[1] + sql := fmt.Sprintf( + `SELECT setval('%s', GREATEST(nextval('%s'), (SELECT COALESCE(MAX(seq_id), 0) FROM %s)))`, + seq, seq, table, + ) + if err := db.Exec(sql).Error; err != nil { + logger.Warnf(context.Background(), "Failed to sync sequence %s: %v", seq, err) + } else { + logger.Infof(context.Background(), "Synced sequence %s with table %s", seq, table) + } + } +} + // resetPendingTasks resets the state of any knowledge items or sync logs stuck in processing // due to an unexpected application restart when using in-memory queues (Lite mode). func resetPendingTasks(db *gorm.DB) { diff --git a/internal/logger/llm_logger.go b/internal/logger/llm_logger.go new file mode 100644 index 00000000..12ddd55b --- /dev/null +++ b/internal/logger/llm_logger.go @@ -0,0 +1,247 @@ +package logger + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +var llmDebug struct { + mu sync.Mutex + enabled bool + dir string +} + +func init() { + configureLLMDebugLog() +} + +func configureLLMDebugLog() { + val := strings.TrimSpace(os.Getenv("LLM_DEBUG_LOG")) + if val == "" || val == "false" || val == "0" { + return + } + + var dir string + if val == "true" || val == "1" { + dir = resolveLLMDebugDir() + } else { + dir = val + } + if dir == "" { + dir = "llm_debug" + } + + if err := os.MkdirAll(dir, 0o755); err != nil { + fmt.Fprintf(os.Stderr, "llm_debug: failed to create dir %s: %v\n", dir, err) + return + } + + llmDebug.dir = dir + llmDebug.enabled = true + + go cleanupOldDebugFiles(dir, 7*24*time.Hour) + + fmt.Fprintf(os.Stderr, "llm_debug: LLM debug log enabled → %s/\n", dir) +} + +func resolveLLMDebugDir() string { + if logPath := strings.TrimSpace(os.Getenv("LOG_PATH")); logPath != "" { + return filepath.Join(filepath.Dir(logPath), "llm_debug") + } + if macPath := defaultMacAppLogPath(); macPath != "" { + return filepath.Join(filepath.Dir(macPath), "llm_debug") + } + return "llm_debug" +} + +// cleanupOldDebugFiles removes files older than maxAge from the debug directory. +func cleanupOldDebugFiles(dir string, maxAge time.Duration) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + cutoff := time.Now().Add(-maxAge) + for _, e := range entries { + if e.IsDir() { + continue + } + info, err := e.Info() + if err != nil { + continue + } + if info.ModTime().Before(cutoff) { + _ = os.Remove(filepath.Join(dir, e.Name())) + } + } +} + +// LLMDebugEnabled returns true when the dedicated LLM debug log is active. +func LLMDebugEnabled() bool { + return llmDebug.enabled +} + +// LLMDebugLog writes a complete model call record to a per-request log file. +// All calls sharing the same request_id are appended to the same file. +func LLMDebugLog(ctx context.Context, record *LLMCallRecord) { + if !llmDebug.enabled || record == nil { + return + } + + text := formatRecord(record) + + reqID := extractRequestID(ctx) + filename := buildFilename(reqID) + + llmDebug.mu.Lock() + defer llmDebug.mu.Unlock() + + path := filepath.Join(llmDebug.dir, filename) + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + fmt.Fprintf(os.Stderr, "llm_debug: open %s: %v\n", path, err) + return + } + defer f.Close() + _, _ = f.WriteString(text) +} + +func buildFilename(reqID string) string { + if reqID != "" { + return reqID + ".log" + } + return time.Now().Format("20060102_150405.000") + ".log" +} + +func formatRecord(r *LLMCallRecord) string { + var b strings.Builder + b.Grow(4096) + + separator := fmt.Sprintf("================ %s ================", r.CallType) + b.WriteString("\n") + b.WriteString(separator) + b.WriteString("\n") + b.WriteString(fmt.Sprintf("Time: %s\n", time.Now().Format("2006-01-02 15:04:05.000"))) + b.WriteString(fmt.Sprintf("Model: %s\n", r.Model)) + if r.Duration > 0 { + b.WriteString(fmt.Sprintf("Duration: %s\n", r.Duration.Round(time.Millisecond))) + } + + for _, s := range r.Sections { + b.WriteString(fmt.Sprintf("\n---------- %s ----------\n", s.Title)) + b.WriteString(s.Content) + if !strings.HasSuffix(s.Content, "\n") { + b.WriteString("\n") + } + } + + if r.Error != "" { + b.WriteString("\n---------- Error ----------\n") + b.WriteString(r.Error) + b.WriteString("\n") + } + + b.WriteString(strings.Repeat("=", len(separator))) + b.WriteString("\n") + + return b.String() +} + +func extractRequestID(ctx context.Context) string { + entry := GetLogger(ctx) + if v, ok := entry.Data["request_id"]; ok { + return fmt.Sprintf("%v", v) + } + return "" +} + +// ---------- Record types ---------- + +// LLMCallRecord holds all information for one model API call. +type LLMCallRecord struct { + CallType string // "Chat", "Chat Stream", "Embedding", "Rerank", "VLM" + Model string + Duration time.Duration + Sections []RecordSection + Error string +} + +// RecordSection is a titled block of text within a call record. +type RecordSection struct { + Title string + Content string +} + +// ---------- Shared helpers for building sections ---------- + +// LLMMessage is a simplified chat message for logging. +type LLMMessage struct { + Role string + Content string + Name string + ToolCallID string + Images []string + ToolCalls []LLMToolCallInfo +} + +// LLMToolCallInfo holds tool call info for logging. +type LLMToolCallInfo struct { + ID string + FuncName string + Arguments string +} + +// FormatMessages formats chat messages into a readable block. +func FormatMessages(messages []LLMMessage) string { + var b strings.Builder + for _, m := range messages { + b.WriteString(fmt.Sprintf("[%s]", m.Role)) + if m.Name != "" { + b.WriteString(fmt.Sprintf(" name=%s", m.Name)) + } + if m.ToolCallID != "" { + b.WriteString(fmt.Sprintf(" tool_call_id=%s", m.ToolCallID)) + } + b.WriteString("\n") + + if m.Content != "" { + b.WriteString(m.Content) + b.WriteString("\n") + } + for _, img := range m.Images { + if len([]rune(img)) > 80 { + b.WriteString(fmt.Sprintf("[image: %s (%d bytes)]\n", TruncateRunes(img, 80), len(img))) + } else { + b.WriteString(fmt.Sprintf("[image: %s]\n", img)) + } + } + for _, tc := range m.ToolCalls { + b.WriteString(fmt.Sprintf(" -> tool_call: id=%s, func=%s, args=%s\n", tc.ID, tc.FuncName, tc.Arguments)) + } + b.WriteString("\n") + } + return b.String() +} + +// FormatToolCalls formats response tool calls into a readable block. +func FormatToolCalls(tcs []LLMToolCallInfo) string { + var b strings.Builder + for _, tc := range tcs { + b.WriteString(fmt.Sprintf("[tool_call] id=%s, func=%s\n%s\n\n", tc.ID, tc.FuncName, tc.Arguments)) + } + return b.String() +} + +// TruncateRunes truncates a string to maxRunes runes, appending "..." if truncated. +// This is safe for multi-byte UTF-8 characters (e.g. Chinese). +func TruncateRunes(s string, maxRunes int) string { + runes := []rune(s) + if len(runes) <= maxRunes { + return s + } + return string(runes[:maxRunes]) + "..." +} diff --git a/internal/models/chat/chat.go b/internal/models/chat/chat.go index f9a2b99c..f4eb8529 100644 --- a/internal/models/chat/chat.go +++ b/internal/models/chat/chat.go @@ -107,14 +107,17 @@ type ChatConfig struct { // NewChat 创建聊天实例 func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, error) { + var c Chat + var err error switch strings.ToLower(string(config.Source)) { case string(types.ModelSourceLocal): - return NewOllamaChat(config, ollamaService) + c, err = NewOllamaChat(config, ollamaService) case string(types.ModelSourceRemote): - return NewRemoteChat(config) + c, err = NewRemoteChat(config) default: return nil, fmt.Errorf("unsupported chat model source: %s", config.Source) } + return wrapChatDebug(c, err) } // NewRemoteChat 根据 provider 创建远程聊天实例 diff --git a/internal/models/chat/llm_debug.go b/internal/models/chat/llm_debug.go new file mode 100644 index 00000000..698a6193 --- /dev/null +++ b/internal/models/chat/llm_debug.go @@ -0,0 +1,214 @@ +package chat + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +func buildLLMMessages(messages []Message) []logger.LLMMessage { + out := make([]logger.LLMMessage, 0, len(messages)) + for _, m := range messages { + lm := logger.LLMMessage{ + Role: m.Role, + Content: m.Content, + Name: m.Name, + ToolCallID: m.ToolCallID, + Images: m.Images, + } + + if lm.Content == "" && len(m.MultiContent) > 0 { + var parts []string + for _, mc := range m.MultiContent { + switch mc.Type { + case "text": + parts = append(parts, mc.Text) + case "image_url": + if mc.ImageURL != nil { + parts = append(parts, fmt.Sprintf("[image_url: %s]", truncateForDebug(mc.ImageURL.URL, 120))) + } + } + } + lm.Content = strings.Join(parts, "\n") + } + + for _, tc := range m.ToolCalls { + lm.ToolCalls = append(lm.ToolCalls, logger.LLMToolCallInfo{ + ID: tc.ID, + FuncName: tc.Function.Name, + Arguments: tc.Function.Arguments, + }) + } + out = append(out, lm) + } + return out +} + +func buildOptionsSection(opts *ChatOptions) string { + if opts == nil { + return "" + } + var parts []string + parts = append(parts, fmt.Sprintf("Temperature=%.2f", opts.Temperature)) + if opts.TopP > 0 { + parts = append(parts, fmt.Sprintf("TopP=%.2f", opts.TopP)) + } + if opts.MaxTokens > 0 { + parts = append(parts, fmt.Sprintf("MaxTokens=%d", opts.MaxTokens)) + } + if opts.MaxCompletionTokens > 0 { + parts = append(parts, fmt.Sprintf("MaxCompletionTokens=%d", opts.MaxCompletionTokens)) + } + if opts.FrequencyPenalty > 0 { + parts = append(parts, fmt.Sprintf("FrequencyPenalty=%.2f", opts.FrequencyPenalty)) + } + if opts.PresencePenalty > 0 { + parts = append(parts, fmt.Sprintf("PresencePenalty=%.2f", opts.PresencePenalty)) + } + if opts.ToolChoice != "" { + parts = append(parts, fmt.Sprintf("ToolChoice=%s", opts.ToolChoice)) + } + if len(opts.Format) > 0 { + parts = append(parts, "ResponseFormat=json_object") + } + return strings.Join(parts, ", ") +} + +func buildToolsSection(opts *ChatOptions) string { + if opts == nil || len(opts.Tools) == 0 { + return "" + } + var b strings.Builder + for i, t := range opts.Tools { + if i > 0 { + b.WriteString("\n") + } + b.WriteString(fmt.Sprintf("- %s: %s", t.Function.Name, t.Function.Description)) + } + return b.String() +} + +func buildResponseToolCalls(tcs []types.LLMToolCall) []logger.LLMToolCallInfo { + if len(tcs) == 0 { + return nil + } + out := make([]logger.LLMToolCallInfo, 0, len(tcs)) + for _, tc := range tcs { + out = append(out, logger.LLMToolCallInfo{ + ID: tc.ID, + FuncName: tc.Function.Name, + Arguments: tc.Function.Arguments, + }) + } + return out +} + +func usageString(u types.TokenUsage) string { + return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d", + u.PromptTokens, u.CompletionTokens, u.TotalTokens) +} + +// logLLMDebugCall logs a complete non-stream LLM chat call. +func logLLMDebugCall(ctx context.Context, model string, messages []Message, opts *ChatOptions, resp *types.ChatResponse, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Chat", + Model: model, + Duration: dur, + } + + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Messages", + Content: logger.FormatMessages(buildLLMMessages(messages)), + }) + if s := buildOptionsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s}) + } + if s := buildToolsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s}) + } + + if resp != nil { + var respText strings.Builder + if resp.Content != "" { + respText.WriteString("[assistant]\n") + respText.WriteString(resp.Content) + respText.WriteString("\n") + } + tcs := buildResponseToolCalls(resp.ToolCalls) + if len(tcs) > 0 { + respText.WriteString(logger.FormatToolCalls(tcs)) + } + if respText.Len() > 0 { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()}) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(resp.Usage)}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +// logLLMDebugStream logs a complete stream LLM chat call after all chunks have been received. +func logLLMDebugStream(ctx context.Context, model string, messages []Message, opts *ChatOptions, fullContent string, toolCalls []types.LLMToolCall, usage *types.TokenUsage, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Chat Stream", + Model: model, + Duration: dur, + } + + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Messages", + Content: logger.FormatMessages(buildLLMMessages(messages)), + }) + if s := buildOptionsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s}) + } + if s := buildToolsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s}) + } + + var respText strings.Builder + if fullContent != "" { + respText.WriteString("[assistant]\n") + respText.WriteString(fullContent) + respText.WriteString("\n") + } + tcs := buildResponseToolCalls(toolCalls) + if len(tcs) > 0 { + respText.WriteString(logger.FormatToolCalls(tcs)) + } + if respText.Len() > 0 { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()}) + } + + if usage != nil { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(*usage)}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +func truncateForDebug(s string, maxRunes int) string { + runes := []rune(s) + if len(runes) <= maxRunes { + return s + } + return string(runes[:maxRunes]) + fmt.Sprintf("...(%d chars)", len(runes)) +} diff --git a/internal/models/chat/llm_debug_wrapper.go b/internal/models/chat/llm_debug_wrapper.go new file mode 100644 index 00000000..a676ef94 --- /dev/null +++ b/internal/models/chat/llm_debug_wrapper.go @@ -0,0 +1,77 @@ +package chat + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// debugChat wraps a Chat implementation and logs all calls to the LLM debug log. +// It works with both RemoteAPIChat and OllamaChat (or any future Chat impl). +type debugChat struct { + inner Chat +} + +func (d *debugChat) GetModelName() string { return d.inner.GetModelName() } +func (d *debugChat) GetModelID() string { return d.inner.GetModelID() } + +func (d *debugChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) { + callStart := time.Now() + resp, err := d.inner.Chat(ctx, messages, opts) + logLLMDebugCall(ctx, d.inner.GetModelName(), messages, opts, resp, err, time.Since(callStart)) + return resp, err +} + +func (d *debugChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) { + callStart := time.Now() + ch, err := d.inner.ChatStream(ctx, messages, opts) + if err != nil { + logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, "", nil, nil, err, time.Since(callStart)) + return ch, err + } + if ch == nil { + return nil, nil + } + + wrapped := make(chan types.StreamResponse) + go func() { + defer close(wrapped) + var content strings.Builder + var usage *types.TokenUsage + var toolCalls []types.LLMToolCall + var streamErr error + + for resp := range ch { + if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" { + content.WriteString(resp.Content) + } + if resp.ResponseType == types.ResponseTypeError { + streamErr = fmt.Errorf("%s", resp.Content) + } + if resp.Usage != nil { + usage = resp.Usage + } + if len(resp.ToolCalls) > 0 { + toolCalls = resp.ToolCalls + } + wrapped <- resp + } + + logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, + content.String(), toolCalls, usage, streamErr, time.Since(callStart)) + }() + + return wrapped, nil +} + +// wrapChatDebug wraps a Chat if LLM debug logging is enabled. +func wrapChatDebug(c Chat, err error) (Chat, error) { + if err != nil || !logger.LLMDebugEnabled() { + return c, err + } + return &debugChat{inner: c}, nil +} diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.go index 1c7dde33..b7cbca38 100644 --- a/internal/models/chat/remote_api.go +++ b/internal/models/chat/remote_api.go @@ -570,11 +570,12 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, FinishReason: state.lastFinishReason, } @@ -614,16 +615,16 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res event, err := reader.ReadEvent() if err != nil { if err == io.EOF { - // 部分模型不发送 [DONE] 标记,直接关闭连接,视为正常结束 if state.usage != nil { logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, } } else { @@ -646,11 +647,12 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, } return diff --git a/internal/models/embedding/embedder.go b/internal/models/embedding/embedder.go index a73d3208..c56b1b1e 100644 --- a/internal/models/embedding/embedder.go +++ b/internal/models/embedding/embedder.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/models/utils/ollama" "github.com/Tencent/WeKnora/internal/types" @@ -54,6 +55,14 @@ type Config struct { // NewEmbedder creates an embedder based on the configuration func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) { + e, err := newEmbedder(config, pooler, ollamaService) + if err != nil || !logger.LLMDebugEnabled() { + return e, err + } + return &debugEmbedder{inner: e}, nil +} + +func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) { var embedder Embedder var err error switch strings.ToLower(string(config.Source)) { diff --git a/internal/models/embedding/llm_debug.go b/internal/models/embedding/llm_debug.go new file mode 100644 index 00000000..1900d268 --- /dev/null +++ b/internal/models/embedding/llm_debug.go @@ -0,0 +1,93 @@ +package embedding + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugEmbedder wraps an Embedder with LLM debug logging. +type debugEmbedder struct { + inner Embedder +} + +func (d *debugEmbedder) Embed(ctx context.Context, text string) ([]float32, error) { + start := time.Now() + result, err := d.inner.Embed(ctx, text) + logEmbeddingDebug(ctx, d.inner.GetModelName(), []string{text}, singleToDouble(result), err, time.Since(start)) + return result, err +} + +func (d *debugEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) { + start := time.Now() + result, err := d.inner.BatchEmbed(ctx, texts) + logEmbeddingDebug(ctx, d.inner.GetModelName(), texts, result, err, time.Since(start)) + return result, err +} + +func (d *debugEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) { + return d.inner.BatchEmbedWithPool(ctx, d, texts) +} + +func (d *debugEmbedder) GetModelName() string { return d.inner.GetModelName() } +func (d *debugEmbedder) GetDimensions() int { return d.inner.GetDimensions() } +func (d *debugEmbedder) GetModelID() string { return d.inner.GetModelID() } + +func singleToDouble(v []float32) [][]float32 { + if v == nil { + return nil + } + return [][]float32{v} +} + +func logEmbeddingDebug(ctx context.Context, model string, inputs []string, outputs [][]float32, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Embedding", + Model: model, + Duration: dur, + } + + // Input section: show each text with a preview + var inputBuf strings.Builder + inputBuf.WriteString(fmt.Sprintf("count=%d\n", len(inputs))) + for i, t := range inputs { + preview := strings.ReplaceAll(t, "\n", "\\n") + preview = logger.TruncateRunes(preview, 200) + inputBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(t)), preview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()}) + + // Output section + if outputs != nil { + var outBuf strings.Builder + outBuf.WriteString(fmt.Sprintf("count=%d\n", len(outputs))) + for i, vec := range outputs { + if len(vec) > 0 { + outBuf.WriteString(fmt.Sprintf("[%d] dims=%d, first_3=[%.6f, %.6f, %.6f]\n", i, len(vec), + safeIdx(vec, 0), safeIdx(vec, 1), safeIdx(vec, 2))) + } else { + outBuf.WriteString(fmt.Sprintf("[%d] empty\n", i)) + } + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Output", Content: outBuf.String()}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +func safeIdx(v []float32, i int) float32 { + if i < len(v) { + return v[i] + } + return 0 +} diff --git a/internal/models/rerank/llm_debug.go b/internal/models/rerank/llm_debug.go new file mode 100644 index 00000000..5abc2731 --- /dev/null +++ b/internal/models/rerank/llm_debug.go @@ -0,0 +1,70 @@ +package rerank + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugReranker wraps a Reranker with LLM debug logging. +type debugReranker struct { + inner Reranker +} + +func (d *debugReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) { + start := time.Now() + result, err := d.inner.Rerank(ctx, query, documents) + logRerankDebug(ctx, d.inner.GetModelName(), query, documents, result, err, time.Since(start)) + return result, err +} + +func (d *debugReranker) GetModelName() string { return d.inner.GetModelName() } +func (d *debugReranker) GetModelID() string { return d.inner.GetModelID() } + +func logRerankDebug(ctx context.Context, model string, query string, documents []string, results []RankResult, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Rerank", + Model: model, + Duration: dur, + } + + // Query section + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Query", + Content: query, + }) + + // Documents section + var docBuf strings.Builder + docBuf.WriteString(fmt.Sprintf("count=%d\n", len(documents))) + for i, doc := range documents { + preview := strings.ReplaceAll(doc, "\n", "\\n") + preview = logger.TruncateRunes(preview, 200) + docBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(doc)), preview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Documents", Content: docBuf.String()}) + + // Results section + if results != nil { + var resBuf strings.Builder + resBuf.WriteString(fmt.Sprintf("count=%d\n", len(results))) + for _, r := range results { + docPreview := strings.ReplaceAll(r.Document.Text, "\n", "\\n") + docPreview = logger.TruncateRunes(docPreview, 200) + resBuf.WriteString(fmt.Sprintf(" [%d] score=%.6f %s\n", r.Index, r.RelevanceScore, docPreview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Results", Content: resBuf.String()}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} diff --git a/internal/models/rerank/reranker.go b/internal/models/rerank/reranker.go index 2c5a1ba2..1e8d1d86 100644 --- a/internal/models/rerank/reranker.go +++ b/internal/models/rerank/reranker.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/types" ) @@ -91,6 +92,14 @@ type RerankerConfig struct { // NewReranker creates a reranker based on the configuration func NewReranker(config *RerankerConfig) (Reranker, error) { + r, err := newReranker(config) + if err != nil || !logger.LLMDebugEnabled() { + return r, err + } + return &debugReranker{inner: r}, nil +} + +func newReranker(config *RerankerConfig) (Reranker, error) { // Use provider field if set, otherwise detect from URL using provider registry providerName := provider.ProviderName(config.Provider) if providerName == "" { diff --git a/internal/models/vlm/llm_debug.go b/internal/models/vlm/llm_debug.go new file mode 100644 index 00000000..18c1a5ca --- /dev/null +++ b/internal/models/vlm/llm_debug.go @@ -0,0 +1,63 @@ +package vlm + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugVLM wraps a VLM with LLM debug logging. +type debugVLM struct { + inner VLM +} + +func (d *debugVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) { + start := time.Now() + result, err := d.inner.Predict(ctx, imgBytes, prompt) + logVLMDebug(ctx, d.inner.GetModelName(), imgBytes, prompt, result, err, time.Since(start)) + return result, err +} + +func (d *debugVLM) GetModelName() string { return d.inner.GetModelName() } +func (d *debugVLM) GetModelID() string { return d.inner.GetModelID() } + +func logVLMDebug(ctx context.Context, model string, imgBytes [][]byte, prompt string, response string, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "VLM", + Model: model, + Duration: dur, + } + + // Input section + var inputBuf strings.Builder + inputBuf.WriteString(fmt.Sprintf("Images: count=%d", len(imgBytes))) + totalSize := 0 + for _, img := range imgBytes { + totalSize += len(img) + } + inputBuf.WriteString(fmt.Sprintf(", total_size=%d bytes\n\n", totalSize)) + inputBuf.WriteString("[prompt]\n") + inputBuf.WriteString(prompt) + inputBuf.WriteString("\n") + record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()}) + + // Response section + if response != "" { + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Response", + Content: response, + }) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} diff --git a/internal/models/vlm/vlm.go b/internal/models/vlm/vlm.go index 3281240a..16e5f5c1 100644 --- a/internal/models/vlm/vlm.go +++ b/internal/models/vlm/vlm.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/models/utils/ollama" "github.com/Tencent/WeKnora/internal/types" @@ -35,6 +36,14 @@ type Config struct { // NewVLM creates a VLM instance based on the provided configuration. func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) { + v, err := newVLM(config, ollamaService) + if err != nil || !logger.LLMDebugEnabled() { + return v, err + } + return &debugVLM{inner: v}, nil +} + +func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) { ifType := strings.ToLower(config.InterfaceType) if ifType == "ollama" || config.Source == types.ModelSourceLocal { diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.go new file mode 100644 index 00000000..18295ec2 --- /dev/null +++ b/internal/searchutil/imageinfo.go @@ -0,0 +1,156 @@ +package searchutil + +import ( + "context" + "encoding/json" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// CollectImageInfoByChunkIDs collects merged image_info JSON for each given +// chunk ID by querying child chunks (image_ocr / image_caption). It supports +// two-level resolution: +// - If chunkIDs are text chunks, their direct children are image chunks → one query. +// - If chunkIDs are parent_text chunks, their children are text chunks +// whose children are image chunks → two queries. +// +// Returns a map of input chunkID → merged image_info JSON string. +func CollectImageInfoByChunkIDs( + ctx context.Context, + chunkRepo interfaces.ChunkRepository, + tenantID uint64, + chunkIDs []string, +) map[string]string { + if len(chunkIDs) == 0 { + return nil + } + + children, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, chunkIDs) + if err != nil || len(children) == 0 { + return nil + } + + type imageAgg struct { + byURL map[string]types.ImageInfo + } + aggMap := make(map[string]*imageAgg) + + addInfo := func(targetID string, child *types.Chunk) { + if child.ImageInfo == "" { + return + } + var infos []types.ImageInfo + if err := json.Unmarshal([]byte(child.ImageInfo), &infos); err != nil || len(infos) == 0 { + return + } + agg, ok := aggMap[targetID] + if !ok { + agg = &imageAgg{byURL: make(map[string]types.ImageInfo)} + aggMap[targetID] = agg + } + for _, info := range infos { + key := info.URL + if key == "" { + key = info.OriginalURL + } + if key == "" { + continue + } + existing, exists := agg.byURL[key] + if !exists { + agg.byURL[key] = info + } else { + if info.OCRText != "" { + existing.OCRText = info.OCRText + } + if info.Caption != "" { + existing.Caption = info.Caption + } + agg.byURL[key] = existing + } + } + } + + var textChildIDs []string + textToParent := make(map[string]string) + + for _, child := range children { + switch child.ChunkType { + case types.ChunkTypeImageOCR, types.ChunkTypeImageCaption: + addInfo(child.ParentChunkID, child) + case types.ChunkTypeText: + textChildIDs = append(textChildIDs, child.ID) + textToParent[child.ID] = child.ParentChunkID + } + } + + if len(textChildIDs) > 0 { + grandChildren, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, textChildIDs) + if err == nil { + for _, gc := range grandChildren { + if gc.ChunkType != types.ChunkTypeImageOCR && gc.ChunkType != types.ChunkTypeImageCaption { + continue + } + if parentTextID, ok := textToParent[gc.ParentChunkID]; ok { + addInfo(parentTextID, gc) + } + } + } + } + + out := make(map[string]string, len(aggMap)) + for id, agg := range aggMap { + if len(agg.byURL) == 0 { + continue + } + merged := make([]types.ImageInfo, 0, len(agg.byURL)) + for _, info := range agg.byURL { + merged = append(merged, info) + } + data, err := json.Marshal(merged) + if err != nil { + continue + } + out[id] = string(data) + } + return out +} + +// EnrichSearchResultsImageInfo fills in ImageInfo for SearchResults that have +// none by batch-querying child image chunks. +func EnrichSearchResultsImageInfo( + ctx context.Context, + chunkRepo interfaces.ChunkRepository, + tenantID uint64, + results []*types.SearchResult, +) { + var chunkIDs []string + seen := make(map[string]bool) + for _, r := range results { + if r.ImageInfo != "" { + continue + } + if !seen[r.ID] { + seen[r.ID] = true + chunkIDs = append(chunkIDs, r.ID) + } + } + if len(chunkIDs) == 0 { + return + } + + infoMap := CollectImageInfoByChunkIDs(ctx, chunkRepo, tenantID, chunkIDs) + if len(infoMap) == 0 { + return + } + + for _, r := range results { + if r.ImageInfo != "" { + continue + } + if merged, ok := infoMap[r.ID]; ok { + r.ImageInfo = merged + } + } +} diff --git a/internal/types/tag.go b/internal/types/tag.go index 75fc2da6..263f4252 100644 --- a/internal/types/tag.go +++ b/internal/types/tag.go @@ -32,7 +32,12 @@ type KnowledgeTag struct { // BeforeCreate ensures SeqID is populated for databases that don't support // autoIncrement on non-primary-key columns (e.g. SQLite). +// On PostgreSQL/MySQL the DB sequence handles this, so we skip to avoid +// duplicate key races under concurrent inserts. func (t *KnowledgeTag) BeforeCreate(tx *gorm.DB) error { + if tx.Dialector.Name() != "sqlite" { + return nil + } if t.SeqID == 0 { var maxSeqID *int64 tx.Unscoped().Model(&KnowledgeTag{}). From 4f5599426664f090d83918f5ea32674cdbb12870 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 22:39:19 +0800 Subject: [PATCH 016/192] feat(prompt): enhance question rewriting and intent classification in prompt templates - Updated the prompt template to clarify the task of understanding and rewriting user questions, improving the instructions for coreference resolution and ellipsis completion. - Renamed sections for better clarity, changing "Rewriting Goals" to "Query Understanding." - Added critical notes for intent classification regarding image and document attachments, ensuring accurate processing based on the presence of attachments. - Improved examples to reflect the updated intent classification logic, enhancing the overall user experience in query handling. --- config/prompt_templates/rewrite.yaml | 14 +- internal/application/repository/chunk.go | 23 ++- .../chat_pipeline/into_chat_message.go | 106 +--------- .../service/chat_pipeline/query_understand.go | 4 + internal/application/service/custom_agent.go | 77 ++++---- internal/application/service/knowledge.go | 130 ++++--------- internal/searchutil/imageinfo.go | 184 ++++++++++++++++++ 7 files changed, 297 insertions(+), 241 deletions(-) diff --git a/config/prompt_templates/rewrite.yaml b/config/prompt_templates/rewrite.yaml index 94b9950e..e026f347 100644 --- a/config/prompt_templates/rewrite.yaml +++ b/config/prompt_templates/rewrite.yaml @@ -19,11 +19,11 @@ templates: default: true content: | You are an intelligent assistant that performs THREE tasks on the user's question: - 1. Rewrite the question (coreference resolution and ellipsis completion) + 1. Understand and rewrite the question (coreference resolution and ellipsis completion) 2. Classify the intent of the question 3. Analyze attached images (when present) - ## Task 1: Rewriting Goals + ## Task 1: Query Understanding Based on the conversation history, rewrite the current user question: - Perform coreference resolution: replace pronouns such as "it", "this", "that", "they", "them", etc. with explicit subjects - Complete omitted key information to ensure the question is semantically complete @@ -43,8 +43,8 @@ templates: 4. `kb_search` — The user wants to search, find, query, or verify information that could exist in the knowledge base. **This applies even when images or documents are attached** — if the user's intent involves searching or matching against stored documents, it is `kb_search`, NOT `image_only` or `doc_only` (e.g. "知识库里有这个文件吗", "帮我查一下这个", "能找到相关的资料吗"). 5. `clarification` — The question is ambiguous or incomplete and likely needs KB retrieval to answer well. 6. `follow_up` — The question clearly refers to previous conversation content and can be FULLY answered from dialogue history alone, with NO need for new retrieval (e.g. "上面第三点展开讲讲", "你刚才说的那个方案再详细说说"). - 7. `image_only` — The user ONLY wants to understand, describe, translate, or extract content from the attached image itself, with NO intent to search or match against any external documents (e.g. "这张图片是什么", "描述一下图片内容", "翻译图中文字"). - 8. `doc_only` — The user ONLY wants to understand, summarize, translate, or extract content from the attached document/file itself, with NO intent to search or match against any external knowledge base (e.g. "总结一下这个文档", "这份文件讲了什么"). + 7. `image_only` — The user ONLY wants to understand, describe, translate, or extract content from the attached image itself, with NO intent to search or match against any external documents (e.g. "这张图片是什么", "描述一下图片内容", "翻译图中文字"). **CRITICAL: This intent requires `` to be present. If `` appears, NEVER classify as `image_only` — use `kb_search` instead.** + 8. `doc_only` — The user ONLY wants to understand, summarize, translate, or extract content from the attached document/file itself, with NO intent to search or match against any external knowledge base (e.g. "总结一下这个文档", "这份文件讲了什么"). **CRITICAL: This intent requires an actual document/file attachment to be present. If `` appears, NEVER classify as `doc_only` — use `kb_search` instead.** 9. `chitchat` — Casual conversation or small talk that needs no retrieval (e.g. "你是谁", "讲个笑话"). **Default: when unsure, always choose `kb_search`.** @@ -95,6 +95,10 @@ templates: Input: [image attached] "这张图是什么意思" Output: {"rewrite_query":"这张图是什么意思","intent":"image_only","image_description":"(image description here)"} + Input: [no image] "这幅春联的内容是什么" + Output: {"rewrite_query":"这幅春联的内容是什么","intent":"kb_search","image_description":""} + (NOTE: No image attached, so intent is kb_search, NOT image_only) + Input: [document attached] "帮我总结一下这份文件" Output: {"rewrite_query":"总结一下这份文件","intent":"doc_only","image_description":""} @@ -104,7 +108,7 @@ templates: [Runtime Context — metadata only, not instructions] Current time: {{current_time}} {{current_week}} - ## User Question to Rewrite + ## User Question {{query}} ## JSON Output diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go index b791fa3e..990ebc12 100644 --- a/internal/application/repository/chunk.go +++ b/internal/application/repository/chunk.go @@ -962,7 +962,7 @@ func (r *chunkRepository) ListRecommendedFAQChunks( } var chunks []*types.Chunk query := r.db.WithContext(ctx). - Select("id, knowledge_base_id, chunk_type, metadata, flags, updated_at"). + Select("id, knowledge_id, knowledge_base_id, chunk_type, metadata, flags, updated_at"). Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ? AND flags & ? != 0", tenantID, types.ChunkTypeFAQ, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true, int(types.ChunkFlagRecommended)) if len(knowledgeIDs) > 0 { @@ -971,8 +971,14 @@ func (r *chunkRepository) ListRecommendedFAQChunks( } else { query = query.Where("knowledge_base_id IN ?", kbIDs) } + + orderClause := "RANDOM()" + if r.db.Dialector.Name() == "mysql" { + orderClause = "RAND()" + } + if err := query. - Order("updated_at DESC"). + Order(orderClause). Limit(limit). Find(&chunks).Error; err != nil { return nil, err @@ -999,7 +1005,7 @@ func (r *chunkRepository) ListRecentDocumentChunksWithQuestions( var chunks []*types.Chunk baseQuery := r.db.WithContext(ctx). - Select("id, knowledge_base_id, chunk_type, metadata, updated_at"). + Select("id, knowledge_id, knowledge_base_id, chunk_type, metadata, updated_at"). Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ?", tenantID, types.ChunkTypeText, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true) @@ -1012,12 +1018,17 @@ func (r *chunkRepository) ListRecentDocumentChunksWithQuestions( baseQuery = baseQuery.Where("knowledge_base_id IN ?", kbIDs) } + orderClause := "RANDOM()" + if r.db.Dialector.Name() == "mysql" { + orderClause = "RAND()" + } + // Query chunks that have non-empty generated_questions in metadata switch r.db.Name() { case "postgres": if err := baseQuery. Where("metadata IS NOT NULL AND metadata::text != '{}' AND jsonb_array_length(COALESCE(metadata->'generated_questions', '[]'::jsonb)) > 0"). - Order("updated_at DESC"). + Order(orderClause). Limit(limit). Find(&chunks).Error; err != nil { return nil, err @@ -1025,7 +1036,7 @@ func (r *chunkRepository) ListRecentDocumentChunksWithQuestions( case "mysql": if err := baseQuery. Where("metadata IS NOT NULL AND JSON_LENGTH(JSON_EXTRACT(metadata, '$.generated_questions')) > 0"). - Order("updated_at DESC"). + Order(orderClause). Limit(limit). Find(&chunks).Error; err != nil { return nil, err @@ -1033,7 +1044,7 @@ func (r *chunkRepository) ListRecentDocumentChunksWithQuestions( default: // sqlite if err := baseQuery. Where("metadata IS NOT NULL AND json_array_length(json_extract(metadata, '$.generated_questions')) > 0"). - Order("updated_at DESC"). + Order(orderClause). Limit(limit). Find(&chunks).Error; err != nil { return nil, err diff --git a/internal/application/service/chat_pipeline/into_chat_message.go b/internal/application/service/chat_pipeline/into_chat_message.go index 9139a59c..9baec373 100644 --- a/internal/application/service/chat_pipeline/into_chat_message.go +++ b/internal/application/service/chat_pipeline/into_chat_message.go @@ -2,11 +2,10 @@ package chatpipeline import ( "context" - "encoding/json" "fmt" - "regexp" "strings" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/utils" @@ -303,104 +302,7 @@ func getEnrichedPassageForChat(ctx context.Context, result *types.SearchResult) return enrichContentWithImageInfo(ctx, result.Content, result.ImageInfo) } -// 正则表达式用于匹配Markdown图片链接 -var markdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`) - -// enrichContentWithImageInfo 将图片信息以 XML 标签的形式嵌入文本内容。 -// 对于内容中已有的 Markdown 图片链接,在其后附加 / ; -// 对于未出现在内容中的图片,以 块追加到末尾。 -func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJSON string) string { - var imageInfos []types.ImageInfo - if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil { - pipelineWarn(ctx, "IntoChatMessage", "image_parse_error", map[string]interface{}{ - "error": err.Error(), - }) - return content - } - if len(imageInfos) == 0 { - return content - } - - imageInfoMap := make(map[string]*types.ImageInfo) - for i := range imageInfos { - if imageInfos[i].URL != "" { - imageInfoMap[imageInfos[i].URL] = &imageInfos[i] - } - if imageInfos[i].OriginalURL != "" { - imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i] - } - } - - matches := markdownImageRegex.FindAllStringSubmatch(content, -1) - processedURLs := make(map[string]bool) - - pipelineInfo(ctx, "IntoChatMessage", "image_markdown_links", map[string]interface{}{ - "match_count": len(matches), - }) - - for _, match := range matches { - if len(match) < 3 { - continue - } - imgURL := match[2] - processedURLs[imgURL] = true - - imgInfo, found := imageInfoMap[imgURL] - var b strings.Builder - b.WriteString(fmt.Sprintf("\n", imgURL)) - b.WriteString(fmt.Sprintf("%s\n", match[0])) - if found && imgInfo != nil { - b.WriteString(buildImageInfoXML(imgInfo)) - } - b.WriteString("") - content = strings.Replace(content, match[0], b.String(), 1) - } - - // Append image info not found as inline Markdown links - var extras []string - for _, imgInfo := range imageInfos { - if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] { - continue - } - url := imgInfo.URL - if url == "" { - url = imgInfo.OriginalURL - } - if block := buildImageInfoXMLWithURL(url, &imgInfo); block != "" { - extras = append(extras, block) - } - } - if len(extras) > 0 { - if content != "" { - content += "\n" - } - content += strings.Join(extras, "\n") - } - - pipelineInfo(ctx, "IntoChatMessage", "image_enrich_summary", map[string]interface{}{ - "markdown_images": len(matches), - "additional_imgs": len(extras), - }) - return content -} - -// buildImageInfoXML returns XML-tagged caption / ocr for one image. -func buildImageInfoXML(img *types.ImageInfo) string { - var b strings.Builder - if img.Caption != "" { - b.WriteString(fmt.Sprintf("%s\n", img.Caption)) - } - if img.OCRText != "" { - b.WriteString(fmt.Sprintf("%s\n", img.OCRText)) - } - return b.String() -} - -// buildImageInfoXMLWithURL wraps image info in an element carrying the URL. -func buildImageInfoXMLWithURL(url string, img *types.ImageInfo) string { - inner := buildImageInfoXML(img) - if inner == "" { - return "" - } - return fmt.Sprintf("\n%s", url, inner) +// enrichContentWithImageInfo delegates to the shared searchutil implementation. +func enrichContentWithImageInfo(_ context.Context, content string, imageInfoJSON string) string { + return searchutil.EnrichContentWithImageInfo(content, imageInfoJSON) } diff --git a/internal/application/service/chat_pipeline/query_understand.go b/internal/application/service/chat_pipeline/query_understand.go index 795b379c..805fa49b 100644 --- a/internal/application/service/chat_pipeline/query_understand.go +++ b/internal/application/service/chat_pipeline/query_understand.go @@ -321,9 +321,13 @@ func (p *PluginQueryUnderstand) buildPrompts(chatManage *types.ChatManage, histo queryContent := chatManage.Query if len(chatManage.Images) > 0 { queryContent += fmt.Sprintf("\n\n", len(chatManage.Images)) + } else { + queryContent += "\n\n" } if len(chatManage.Attachments) > 0 { queryContent += chatManage.Attachments.BuildPrompt() + } else { + queryContent += "\n" } vals := types.PlaceholderValues{ diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index b302d495..bcf74138 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -3,7 +3,7 @@ package service import ( "context" "errors" - "sort" + "math/rand" "strings" "time" @@ -503,22 +503,19 @@ func (s *customAgentService) GetSuggestedQuestions( return s.truncateQuestions(result, limit), nil } - // 3. Collect all candidate chunks from both FAQ and Document KBs, - // then sort by updated_at uniformly (not FAQ-first). - type candidate struct { - question types.SuggestedQuestion - updatedAt time.Time - } - var candidates []candidate + // 3. Collect candidate chunks from both FAQ and Document KBs, + // grouped by knowledge_id for diversity. + // knowledgeID -> list of questions + buckets := make(map[string][]types.SuggestedQuestion) // Determine query scope queryKBIDs := effectiveKBIDs queryKnowledgeIDs := knowledgeIDs - // Fetch more than needed from each source, we'll merge-sort and truncate - fetchLimit := remaining * 2 - if fetchLimit < 10 { - fetchLimit = 10 + // Fetch a large pool so DB-level random sampling covers multiple documents. + fetchLimit := remaining * 5 + if fetchLimit < 20 { + fetchLimit = 20 } // Collect FAQ recommended chunks @@ -537,13 +534,10 @@ func (s *customAgentService) GetSuggestedQuestions( continue } seen[meta.StandardQuestion] = true - candidates = append(candidates, candidate{ - question: types.SuggestedQuestion{ - Question: meta.StandardQuestion, - Source: "faq", - KnowledgeBaseID: chunk.KnowledgeBaseID, - }, - updatedAt: chunk.UpdatedAt, + buckets[chunk.KnowledgeID] = append(buckets[chunk.KnowledgeID], types.SuggestedQuestion{ + Question: meta.StandardQuestion, + Source: "faq", + KnowledgeBaseID: chunk.KnowledgeBaseID, }) } } @@ -565,28 +559,45 @@ func (s *customAgentService) GetSuggestedQuestions( continue } seen[q] = true - candidates = append(candidates, candidate{ - question: types.SuggestedQuestion{ - Question: q, - Source: "document", - KnowledgeBaseID: chunk.KnowledgeBaseID, - }, - updatedAt: chunk.UpdatedAt, + buckets[chunk.KnowledgeID] = append(buckets[chunk.KnowledgeID], types.SuggestedQuestion{ + Question: q, + Source: "document", + KnowledgeBaseID: chunk.KnowledgeBaseID, }) } } - // 4. Sort all candidates by updated_at descending (newest first) - sort.Slice(candidates, func(i, j int) bool { - return candidates[i].updatedAt.After(candidates[j].updatedAt) + // 4. Shuffle within each bucket, then round-robin across buckets + // to ensure diversity across different documents. + bucketKeys := make([]string, 0, len(buckets)) + for k, qs := range buckets { + bucketKeys = append(bucketKeys, k) + rand.Shuffle(len(qs), func(i, j int) { qs[i], qs[j] = qs[j], qs[i] }) + buckets[k] = qs + } + rand.Shuffle(len(bucketKeys), func(i, j int) { + bucketKeys[i], bucketKeys[j] = bucketKeys[j], bucketKeys[i] }) - // 5. Pick top N - for _, c := range candidates { - if len(result) >= limit { + // Round-robin pick one question from each document in turn. + offsets := make(map[string]int, len(bucketKeys)) + for len(result) < limit { + picked := false + for _, key := range bucketKeys { + if len(result) >= limit { + break + } + qs := buckets[key] + idx := offsets[key] + if idx < len(qs) { + result = append(result, qs[idx]) + offsets[key] = idx + 1 + picked = true + } + } + if !picked { break } - result = append(result, c.question) } return s.truncateQuestions(result, limit), nil diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index 703e443b..33cb7d3c 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -13,7 +13,6 @@ import ( "net/url" "os" "path" - "regexp" "runtime" "slices" "sort" @@ -30,6 +29,7 @@ import ( "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/chat" "github.com/Tencent/WeKnora/internal/models/embedding" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/tracing" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -1943,7 +1943,7 @@ func (s *knowledgeService) processChunks(ctx context.Context, } // defaultMaxInputChars is the default maximum characters used as input for summary generation. -const defaultMaxInputChars = 16384 +const defaultMaxInputChars = 1024 * 24 // getSummary generates a summary for knowledge content using an AI model func (s *knowledgeService) getSummary(ctx context.Context, @@ -1960,52 +1960,36 @@ func (s *knowledgeService) getSummary(ctx context.Context, maxInputChars = s.config.Conversation.Summary.MaxInputChars } - // concat chunk contents - chunkContents := "" - allImageInfos := make([]*types.ImageInfo, 0) - - // then, sort chunks by StartAt + // Sort chunks by StartAt for proper concatenation sortedChunks := make([]*types.Chunk, len(chunks)) copy(sortedChunks, chunks) sort.Slice(sortedChunks, func(i, j int) bool { return sortedChunks[i].StartAt < sortedChunks[j].StartAt }) - // concat ALL chunk contents (no early truncation) and collect image infos + // Concatenate original chunk contents by StartAt offset to reconstruct the + // document, then enrich with image info in a second pass. Enrichment must + // happen AFTER concatenation because StartAt is based on original document + // offsets — enriched (longer) content would break the positioning. + chunkContents := "" for _, chunk := range sortedChunks { - // Ensure we don't slice beyond the current content length runes := []rune(chunkContents) if chunk.StartAt <= len(runes) { chunkContents = string(runes[:chunk.StartAt]) + chunk.Content } else { - // If StartAt is beyond current content, just append chunkContents = chunkContents + chunk.Content } - if chunk.ImageInfo != "" { - var images []*types.ImageInfo - if err := json.Unmarshal([]byte(chunk.ImageInfo), &images); err == nil { - allImageInfos = append(allImageInfos, images...) - } - } } - // remove markdown image syntax - re := regexp.MustCompile(`!\[[^\]]*\]\([^)]+\)`) - chunkContents = re.ReplaceAllString(chunkContents, "") - // collect all image infos - if len(allImageInfos) > 0 { - // add image infos to chunk contents - var imageAnnotations string - for _, img := range allImageInfos { - if img.Caption != "" { - imageAnnotations += fmt.Sprintf("\n[Image Description: %s]", img.Caption) - } - if img.OCRText != "" { - imageAnnotations += fmt.Sprintf("\n[Image OCR Text: %s]", img.OCRText) - } - } - // concat chunk contents and image annotations - chunkContents = chunkContents + imageAnnotations + // Collect image_info from image_ocr/image_caption children and enrich + chunkIDs := make([]string, len(sortedChunks)) + for i, c := range sortedChunks { + chunkIDs[i] = c.ID + } + imageInfoMap := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, knowledge.TenantID, chunkIDs) + mergedImageInfo := searchutil.MergeImageInfoJSON(imageInfoMap) + if mergedImageInfo != "" { + chunkContents = searchutil.EnrichContentCaptionOnly(chunkContents, mergedImageInfo) } // Apply length limit: sample long content to fit within maxInputChars @@ -2108,63 +2092,6 @@ func sampleLongContent(content string, maxChars int) string { return head + omitMarker + middle + omitMarker + tail } -// enqueueQuestionGenerationTask enqueues an async task for question generation -func (s *knowledgeService) enqueueQuestionGenerationTask(ctx context.Context, - kbID, knowledgeID string, questionCount int, -) { - tenantID := ctx.Value(types.TenantIDContextKey).(uint64) - lang, _ := types.LanguageFromContext(ctx) - payload := types.QuestionGenerationPayload{ - TenantID: tenantID, - KnowledgeBaseID: kbID, - KnowledgeID: knowledgeID, - QuestionCount: questionCount, - Language: lang, - } - - payloadBytes, err := json.Marshal(payload) - if err != nil { - logger.Errorf(ctx, "Failed to marshal question generation payload: %v", err) - return - } - - task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3)) - info, err := s.task.Enqueue(task) - if err != nil { - logger.Errorf(ctx, "Failed to enqueue question generation task: %v", err) - return - } - logger.Infof(ctx, "Enqueued question generation task: %s for knowledge: %s", info.ID, knowledgeID) -} - -// enqueueSummaryGenerationTask enqueues an async task for summary generation -func (s *knowledgeService) enqueueSummaryGenerationTask(ctx context.Context, - kbID, knowledgeID string, -) { - tenantID := ctx.Value(types.TenantIDContextKey).(uint64) - lang, _ := types.LanguageFromContext(ctx) - payload := types.SummaryGenerationPayload{ - TenantID: tenantID, - KnowledgeBaseID: kbID, - KnowledgeID: knowledgeID, - Language: lang, - } - - payloadBytes, err := json.Marshal(payload) - if err != nil { - logger.Errorf(ctx, "Failed to marshal summary generation payload: %v", err) - return - } - - task := asynq.NewTask(types.TypeSummaryGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3)) - info, err := s.task.Enqueue(task) - if err != nil { - logger.Errorf(ctx, "Failed to enqueue summary generation task: %v", err) - return - } - logger.Infof(ctx, "Enqueued summary generation task: %s for knowledge: %s", info.ID, knowledgeID) -} - // ProcessSummaryGeneration handles async summary generation task func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asynq.Task) error { var payload types.SummaryGenerationPayload @@ -2452,27 +2379,40 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy questionCount = 10 } + // Collect image info for all text chunks so question generation can + // see caption / OCR text instead of bare image links. + textChunkIDs := make([]string, len(textChunks)) + for i, c := range textChunks { + textChunkIDs[i] = c.ID + } + imageInfoMap := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, payload.TenantID, textChunkIDs) + + enrichContent := func(chunk *types.Chunk) string { + if info, ok := imageInfoMap[chunk.ID]; ok && info != "" { + return searchutil.EnrichContentWithImageInfo(chunk.Content, info) + } + return chunk.Content + } + // Generate questions for each chunk with context var indexInfoList []*types.IndexInfo for i, chunk := range textChunks { // Build context from adjacent chunks var prevContent, nextContent string if i > 0 { - prevContent = textChunks[i-1].Content - // Limit context size + prevContent = enrichContent(textChunks[i-1]) if len(prevContent) > 500 { prevContent = prevContent[len(prevContent)-500:] } } if i < len(textChunks)-1 { - nextContent = textChunks[i+1].Content - // Limit context size + nextContent = enrichContent(textChunks[i+1]) if len(nextContent) > 500 { nextContent = nextContent[:500] } } - questions, err := s.generateQuestionsWithContext(ctx, chatModel, chunk.Content, prevContent, nextContent, knowledge.Title, questionCount) + questions, err := s.generateQuestionsWithContext(ctx, chatModel, enrichContent(chunk), prevContent, nextContent, knowledge.Title, questionCount) if err != nil { logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, err) continue diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.go index 18295ec2..b526ff91 100644 --- a/internal/searchutil/imageinfo.go +++ b/internal/searchutil/imageinfo.go @@ -3,11 +3,17 @@ package searchutil import ( "context" "encoding/json" + "fmt" + "regexp" + "strings" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" ) +// MarkdownImageRegex matches Markdown image links: ![alt](url) +var MarkdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`) + // CollectImageInfoByChunkIDs collects merged image_info JSON for each given // chunk ID by querying child chunks (image_ocr / image_caption). It supports // two-level resolution: @@ -154,3 +160,181 @@ func EnrichSearchResultsImageInfo( } } } + +// MergeImageInfoJSON combines per-chunk image_info JSON strings (from +// CollectImageInfoByChunkIDs) into a single JSON array, deduplicating by URL. +func MergeImageInfoJSON(perChunk map[string]string) string { + if len(perChunk) == 0 { + return "" + } + seen := make(map[string]bool) + var all []types.ImageInfo + for _, raw := range perChunk { + var infos []types.ImageInfo + if err := json.Unmarshal([]byte(raw), &infos); err != nil { + continue + } + for _, info := range infos { + key := info.URL + if key == "" { + key = info.OriginalURL + } + if key != "" && !seen[key] { + seen[key] = true + all = append(all, info) + } + } + } + if len(all) == 0 { + return "" + } + data, err := json.Marshal(all) + if err != nil { + return "" + } + return string(data) +} + +// EnrichContentWithImageInfo embeds image info as XML tags into text content. +// Inline Markdown image links get wrapped in with / ; +// images not found in content are appended as blocks. +func EnrichContentWithImageInfo(content string, imageInfoJSON string) string { + var imageInfos []types.ImageInfo + if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil { + return content + } + if len(imageInfos) == 0 { + return content + } + + imageInfoMap := make(map[string]*types.ImageInfo) + for i := range imageInfos { + if imageInfos[i].URL != "" { + imageInfoMap[imageInfos[i].URL] = &imageInfos[i] + } + if imageInfos[i].OriginalURL != "" { + imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i] + } + } + + matches := MarkdownImageRegex.FindAllStringSubmatch(content, -1) + processedURLs := make(map[string]bool) + + for _, match := range matches { + if len(match) < 3 { + continue + } + imgURL := match[2] + processedURLs[imgURL] = true + + imgInfo, found := imageInfoMap[imgURL] + var b strings.Builder + b.WriteString(fmt.Sprintf("\n", imgURL)) + b.WriteString(fmt.Sprintf("%s\n", match[0])) + if found && imgInfo != nil { + b.WriteString(BuildImageInfoXML(imgInfo)) + } + b.WriteString("") + content = strings.Replace(content, match[0], b.String(), 1) + } + + var extras []string + for _, imgInfo := range imageInfos { + if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] { + continue + } + url := imgInfo.URL + if url == "" { + url = imgInfo.OriginalURL + } + if block := BuildImageInfoXMLWithURL(url, &imgInfo); block != "" { + extras = append(extras, block) + } + } + if len(extras) > 0 { + if content != "" { + content += "\n" + } + content += strings.Join(extras, "\n") + } + return content +} + +// BuildImageInfoXML returns XML-tagged caption / ocr for one image. +func BuildImageInfoXML(img *types.ImageInfo) string { + var b strings.Builder + if img.Caption != "" { + b.WriteString(fmt.Sprintf("%s\n", img.Caption)) + } + if img.OCRText != "" { + b.WriteString(fmt.Sprintf("%s\n", img.OCRText)) + } + return b.String() +} + +// BuildImageInfoXMLWithURL wraps image info in an element carrying the URL. +func BuildImageInfoXMLWithURL(url string, img *types.ImageInfo) string { + inner := BuildImageInfoXML(img) + if inner == "" { + return "" + } + return fmt.Sprintf("\n%s", url, inner) +} + +// EnrichContentCaptionOnly is like EnrichContentWithImageInfo but only +// includes image captions (no OCR text). Original content (including Markdown +// image links) is preserved. Useful for summary generation where OCR would +// add too much noise. +func EnrichContentCaptionOnly(content string, imageInfoJSON string) string { + var imageInfos []types.ImageInfo + if err := json.Unmarshal([]byte(imageInfoJSON), &imageInfos); err != nil { + return content + } + if len(imageInfos) == 0 { + return content + } + + imageInfoMap := make(map[string]*types.ImageInfo) + for i := range imageInfos { + if imageInfos[i].URL != "" { + imageInfoMap[imageInfos[i].URL] = &imageInfos[i] + } + if imageInfos[i].OriginalURL != "" { + imageInfoMap[imageInfos[i].OriginalURL] = &imageInfos[i] + } + } + + matches := MarkdownImageRegex.FindAllStringSubmatch(content, -1) + processedURLs := make(map[string]bool) + + for _, match := range matches { + if len(match) < 3 { + continue + } + imgURL := match[2] + processedURLs[imgURL] = true + + imgInfo, found := imageInfoMap[imgURL] + if found && imgInfo != nil && imgInfo.Caption != "" { + replacement := match[0] + "\n" + fmt.Sprintf("%s", imgInfo.Caption) + content = strings.Replace(content, match[0], replacement, 1) + } + } + + var extras []string + for _, imgInfo := range imageInfos { + if processedURLs[imgInfo.URL] || processedURLs[imgInfo.OriginalURL] { + continue + } + if imgInfo.Caption != "" { + extras = append(extras, fmt.Sprintf("%s", imgInfo.Caption)) + } + } + if len(extras) > 0 { + if content != "" { + content += "\n" + } + content += strings.Join(extras, "\n") + } + return content +} From c5fc05f3d0dccf1feabe317a323db04883de217f Mon Sep 17 00:00:00 2001 From: "ochan.kwon" Date: Wed, 15 Apr 2026 12:44:52 +0900 Subject: [PATCH 017/192] feat: add registry dual-map and engine factory for VectorStore - Extend RetrieveEngineRegistry with byStoreID map for DB store engines - Add StoreRegistry interface and EngineFactory function type - Create engine factory with per-driver SDK client construction - Load VectorStore records from DB into registry at startup - Wire Create/Delete to dynamically register/unregister engines - Add comprehensive unit tests for registry and service --- .../application/service/retriever/registry.go | 74 ++++- .../service/retriever/registry_test.go | 237 ++++++++++++++++ internal/application/service/vectorstore.go | 60 +++- .../application/service/vectorstore_test.go | 263 +++++++++++++++++- internal/container/container.go | 44 +++ internal/container/engine_factory.go | 205 ++++++++++++++ internal/types/interfaces/vectorstore.go | 17 ++ 7 files changed, 868 insertions(+), 32 deletions(-) create mode 100644 internal/application/service/retriever/registry_test.go create mode 100644 internal/container/engine_factory.go diff --git a/internal/application/service/retriever/registry.go b/internal/application/service/retriever/registry.go index 3790ce49..42d7aff6 100644 --- a/internal/application/service/retriever/registry.go +++ b/internal/application/service/retriever/registry.go @@ -8,40 +8,51 @@ import ( "github.com/Tencent/WeKnora/internal/types/interfaces" ) -// RetrieveEngineRegistry implements the retrieval engine registry +// RetrieveEngineRegistry implements the retrieval engine registry. +// It maintains two maps: +// - byEngineType: env stores registered via RETRIEVE_DRIVER (backward compatible) +// - byStoreID: DB stores registered via VectorStore table (instance-based) +// +// Implements both interfaces.RetrieveEngineRegistry and interfaces.StoreRegistry. type RetrieveEngineRegistry struct { - repositories map[types.RetrieverEngineType]interfaces.RetrieveEngineService + byEngineType map[types.RetrieverEngineType]interfaces.RetrieveEngineService + byStoreID map[string]interfaces.RetrieveEngineService mu sync.RWMutex } // NewRetrieveEngineRegistry creates a new retrieval engine registry func NewRetrieveEngineRegistry() interfaces.RetrieveEngineRegistry { return &RetrieveEngineRegistry{ - repositories: make(map[types.RetrieverEngineType]interfaces.RetrieveEngineService), + byEngineType: make(map[types.RetrieverEngineType]interfaces.RetrieveEngineService), + byStoreID: make(map[string]interfaces.RetrieveEngineService), } } -// Register registers a retrieval engine service +// --- interfaces.RetrieveEngineRegistry methods (unchanged behavior) --- + +// Register registers a retrieval engine service by engine type. +// Returns an error if the engine type is already registered. func (r *RetrieveEngineRegistry) Register(repo interfaces.RetrieveEngineService) error { r.mu.Lock() defer r.mu.Unlock() - if _, exists := r.repositories[repo.EngineType()]; exists { + if _, exists := r.byEngineType[repo.EngineType()]; exists { return fmt.Errorf("repository type %s already registered", repo.EngineType()) } - r.repositories[repo.EngineType()] = repo + r.byEngineType[repo.EngineType()] = repo return nil } -// GetRetrieveEngineService retrieves a retrieval engine service by type +// GetRetrieveEngineService retrieves a retrieval engine service by type. +// Only searches the byEngineType map (env stores). func (r *RetrieveEngineRegistry) GetRetrieveEngineService(repoType types.RetrieverEngineType) ( interfaces.RetrieveEngineService, error, ) { r.mu.RLock() defer r.mu.RUnlock() - repo, exists := r.repositories[repoType] + repo, exists := r.byEngineType[repoType] if !exists { return nil, fmt.Errorf("repository of type %s not found", repoType) } @@ -49,16 +60,55 @@ func (r *RetrieveEngineRegistry) GetRetrieveEngineService(repoType types.Retriev return repo, nil } -// GetAllRetrieveEngineServices retrieves all registered retrieval engine services +// GetAllRetrieveEngineServices retrieves all registered retrieval engine services. +// Only returns byEngineType entries (env stores) for backward compatibility. func (r *RetrieveEngineRegistry) GetAllRetrieveEngineServices() []interfaces.RetrieveEngineService { r.mu.RLock() defer r.mu.RUnlock() - // Create a copy to avoid modifying the original map - result := make([]interfaces.RetrieveEngineService, 0, len(r.repositories)) - for _, v := range r.repositories { + result := make([]interfaces.RetrieveEngineService, 0, len(r.byEngineType)) + for _, v := range r.byEngineType { result = append(result, v) } return result } + +// --- interfaces.StoreRegistry methods (new, for VectorStore-based engines) --- + +// RegisterWithStoreID registers an engine service by VectorStore ID. +// Unlike Register(), the same EngineType can be registered multiple times +// with different StoreIDs (e.g., two Elasticsearch clusters). +// Upsert semantics: existing entry is overwritten silently. +func (r *RetrieveEngineRegistry) RegisterWithStoreID(storeID string, svc interfaces.RetrieveEngineService) { + r.mu.Lock() + defer r.mu.Unlock() + + r.byStoreID[storeID] = svc +} + +// GetByStoreID retrieves an engine service by VectorStore ID. +// Callers must verify tenant ownership before using the returned service. +func (r *RetrieveEngineRegistry) GetByStoreID(storeID string) (interfaces.RetrieveEngineService, error) { + r.mu.RLock() + defer r.mu.RUnlock() + + svc, exists := r.byStoreID[storeID] + if !exists { + return nil, fmt.Errorf("store %s not found in registry", storeID) + } + return svc, nil +} + +// UnregisterByStoreID removes an engine service from the byStoreID map. +// Idempotent: returns silently if the storeID is not found. +// +// NOTE: gRPC-based clients (Qdrant, Milvus) hold connections that are not closed here. +// Known Phase 1 limitation — store deletion is rare, connections cleaned up on process exit. +// Phase 2 should add Close() to RetrieveEngineService interface and call it here. +func (r *RetrieveEngineRegistry) UnregisterByStoreID(storeID string) { + r.mu.Lock() + defer r.mu.Unlock() + + delete(r.byStoreID, storeID) +} diff --git a/internal/application/service/retriever/registry_test.go b/internal/application/service/retriever/registry_test.go new file mode 100644 index 00000000..f8d2aa0e --- /dev/null +++ b/internal/application/service/retriever/registry_test.go @@ -0,0 +1,237 @@ +package retriever + +import ( + "context" + "fmt" + "sync" + "testing" + + "github.com/Tencent/WeKnora/internal/models/embedding" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// mockEngineService is a minimal mock for testing registry operations. +// Only EngineType() is meaningful; all other methods are no-ops. +type mockEngineService struct { + engineType types.RetrieverEngineType +} + +func (m *mockEngineService) EngineType() types.RetrieverEngineType { return m.engineType } +func (m *mockEngineService) Retrieve(_ context.Context, _ types.RetrieveParams) ([]*types.RetrieveResult, error) { + return nil, nil +} +func (m *mockEngineService) Support() []types.RetrieverType { return nil } +func (m *mockEngineService) Index(_ context.Context, _ embedding.Embedder, _ *types.IndexInfo, _ []types.RetrieverType) error { + return nil +} +func (m *mockEngineService) BatchIndex(_ context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) error { + return nil +} +func (m *mockEngineService) EstimateStorageSize(_ context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) int64 { + return 0 +} +func (m *mockEngineService) CopyIndices(_ context.Context, _ string, _ map[string]string, _ map[string]string, _ string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteByChunkIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteBySourceIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteByKnowledgeIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) BatchUpdateChunkEnabledStatus(_ context.Context, _ map[string]bool) error { + return nil +} +func (m *mockEngineService) BatchUpdateChunkTagID(_ context.Context, _ map[string]string) error { + return nil +} + +func newMock(engineType types.RetrieverEngineType) interfaces.RetrieveEngineService { + return &mockEngineService{engineType: engineType} +} + +// --- Register (byEngineType) tests --- + +func TestRegistry_Register(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + + t.Run("success", func(t *testing.T) { + err := reg.Register(newMock(types.PostgresRetrieverEngineType)) + assert.NoError(t, err) + }) + + t.Run("duplicate engine type returns error", func(t *testing.T) { + err := reg.Register(newMock(types.PostgresRetrieverEngineType)) + assert.Error(t, err) + assert.Contains(t, err.Error(), "already registered") + }) +} + +func TestRegistry_GetRetrieveEngineService(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + _ = reg.Register(newMock(types.PostgresRetrieverEngineType)) + + t.Run("found", func(t *testing.T) { + svc, err := reg.GetRetrieveEngineService(types.PostgresRetrieverEngineType) + assert.NoError(t, err) + assert.NotNil(t, svc) + }) + + t.Run("not found", func(t *testing.T) { + _, err := reg.GetRetrieveEngineService(types.QdrantRetrieverEngineType) + assert.Error(t, err) + assert.Contains(t, err.Error(), "not found") + }) +} + +func TestRegistry_GetAllRetrieveEngineServices(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + _ = reg.Register(newMock(types.PostgresRetrieverEngineType)) + _ = reg.Register(newMock(types.ElasticsearchRetrieverEngineType)) + + t.Run("returns all byEngineType entries", func(t *testing.T) { + all := reg.GetAllRetrieveEngineServices() + assert.Len(t, all, 2) + }) + + t.Run("returns copy - modifying result does not affect registry", func(t *testing.T) { + all := reg.GetAllRetrieveEngineServices() + all = append(all, newMock(types.QdrantRetrieverEngineType)) + assert.Len(t, reg.GetAllRetrieveEngineServices(), 2) + }) +} + +// --- RegisterWithStoreID (byStoreID) tests --- + +func TestRegistry_RegisterWithStoreID(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + + t.Run("success", func(t *testing.T) { + reg.RegisterWithStoreID("store-1", newMock(types.PostgresRetrieverEngineType)) + svc, err := reg.GetByStoreID("store-1") + assert.NoError(t, err) + assert.NotNil(t, svc) + }) + + t.Run("upsert overwrites existing", func(t *testing.T) { + newSvc := newMock(types.ElasticsearchRetrieverEngineType) + reg.RegisterWithStoreID("store-1", newSvc) + svc, err := reg.GetByStoreID("store-1") + assert.NoError(t, err) + assert.Equal(t, types.ElasticsearchRetrieverEngineType, svc.EngineType()) + }) + + t.Run("same engine type different store IDs", func(t *testing.T) { + reg.RegisterWithStoreID("es-hot", newMock(types.ElasticsearchRetrieverEngineType)) + reg.RegisterWithStoreID("es-warm", newMock(types.ElasticsearchRetrieverEngineType)) + + svc1, err1 := reg.GetByStoreID("es-hot") + svc2, err2 := reg.GetByStoreID("es-warm") + assert.NoError(t, err1) + assert.NoError(t, err2) + assert.NotSame(t, svc1, svc2) + }) +} + +func TestRegistry_GetByStoreID(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + reg.RegisterWithStoreID("store-1", newMock(types.PostgresRetrieverEngineType)) + + t.Run("found", func(t *testing.T) { + svc, err := reg.GetByStoreID("store-1") + assert.NoError(t, err) + assert.NotNil(t, svc) + }) + + t.Run("not found", func(t *testing.T) { + _, err := reg.GetByStoreID("nonexistent") + assert.Error(t, err) + assert.Contains(t, err.Error(), "not found") + }) +} + +func TestRegistry_UnregisterByStoreID(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + reg.RegisterWithStoreID("store-1", newMock(types.PostgresRetrieverEngineType)) + + t.Run("removes registered store", func(t *testing.T) { + reg.UnregisterByStoreID("store-1") + _, err := reg.GetByStoreID("store-1") + assert.Error(t, err) + }) + + t.Run("idempotent on nonexistent store", func(t *testing.T) { + reg.UnregisterByStoreID("nonexistent") // should not panic + }) +} + +// --- Dual map isolation tests --- + +func TestRegistry_DualMapIsolation(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + + _ = reg.Register(newMock(types.PostgresRetrieverEngineType)) + reg.RegisterWithStoreID("store-pg", newMock(types.PostgresRetrieverEngineType)) + reg.RegisterWithStoreID("store-es", newMock(types.ElasticsearchRetrieverEngineType)) + + t.Run("GetAllRetrieveEngineServices returns only byEngineType", func(t *testing.T) { + all := reg.GetAllRetrieveEngineServices() + assert.Len(t, all, 1) + }) + + t.Run("byStoreID does not affect byEngineType lookup", func(t *testing.T) { + _, err := reg.GetRetrieveEngineService(types.ElasticsearchRetrieverEngineType) + assert.Error(t, err) // ES is only in byStoreID, not byEngineType + }) + + t.Run("unregister byStoreID does not affect byEngineType", func(t *testing.T) { + reg.UnregisterByStoreID("store-pg") + svc, err := reg.GetRetrieveEngineService(types.PostgresRetrieverEngineType) + assert.NoError(t, err) + assert.NotNil(t, svc) + }) +} + +// --- Concurrency test --- + +func TestRegistry_ConcurrentAccess(t *testing.T) { + reg := NewRetrieveEngineRegistry().(*RetrieveEngineRegistry) + const goroutines = 10 + + var wg sync.WaitGroup + wg.Add(goroutines * 3) + + for i := 0; i < goroutines; i++ { + storeID := fmt.Sprintf("store-%d", i) + go func() { + defer wg.Done() + reg.RegisterWithStoreID(storeID, newMock(types.PostgresRetrieverEngineType)) + }() + go func() { + defer wg.Done() + _, _ = reg.GetByStoreID(storeID) + }() + go func() { + defer wg.Done() + reg.UnregisterByStoreID(storeID) + }() + } + + wg.Wait() +} + +// --- Interface compliance --- + +func TestRegistry_ImplementsStoreRegistry(t *testing.T) { + reg := NewRetrieveEngineRegistry() + concreteReg, ok := reg.(*RetrieveEngineRegistry) + require.True(t, ok) + + var _ interfaces.StoreRegistry = concreteReg +} diff --git a/internal/application/service/vectorstore.go b/internal/application/service/vectorstore.go index 4bc91a0b..c677d248 100644 --- a/internal/application/service/vectorstore.go +++ b/internal/application/service/vectorstore.go @@ -3,6 +3,7 @@ package service import ( "context" "os" + "time" "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" @@ -13,14 +14,22 @@ import ( // vectorStoreService implements interfaces.VectorStoreService type vectorStoreService struct { - repo interfaces.VectorStoreRepository + repo interfaces.VectorStoreRepository + storeRegistry interfaces.StoreRegistry // for dynamic registry updates on CRUD + factory interfaces.EngineFactory // creates engine services from VectorStore config } // NewVectorStoreService creates a new vector store service func NewVectorStoreService( repo interfaces.VectorStoreRepository, + storeRegistry interfaces.StoreRegistry, + factory interfaces.EngineFactory, ) interfaces.VectorStoreService { - return &vectorStoreService{repo: repo} + return &vectorStoreService{ + repo: repo, + storeRegistry: storeRegistry, + factory: factory, + } } // CreateStore validates and creates a new vector store. @@ -60,10 +69,20 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto // 5. Persist logger.Infof(ctx, "Creating vector store: tenant=%d, name=%s, engine=%s", store.TenantID, secutils.SanitizeForLog(store.Name), store.EngineType) - return s.repo.Create(ctx, store) + if err := s.repo.Create(ctx, store); err != nil { + return err + } + + // 6. Register in registry (best-effort; failure doesn't roll back DB). + // The store is already persisted, and will be loaded on next app restart (self-healing). + s.registerInRegistry(ctx, store) + + return nil } // UpdateStore updates an existing vector store (name only). +// NOTE: If connection_config or index_config become mutable in the future, +// registry re-registration must be added here (unregister old + register new). func (s *vectorStoreService) UpdateStore(ctx context.Context, store *types.VectorStore) error { if store.TenantID == 0 { return errors.NewValidationError("tenant_id is required") @@ -79,8 +98,17 @@ func (s *vectorStoreService) UpdateStore(ctx context.Context, store *types.Vecto // DeleteStore deletes a vector store by tenant + id. // Phase 2: KB binding check will be added here. func (s *vectorStoreService) DeleteStore(ctx context.Context, tenantID uint64, id string) error { - logger.Infof(ctx, "Deleting vector store: tenant=%d, id=%s", tenantID, id) - return s.repo.Delete(ctx, tenantID, id) + if err := s.repo.Delete(ctx, tenantID, id); err != nil { + return err + } + + // Unregister from registry (idempotent) + if s.storeRegistry != nil { + s.storeRegistry.UnregisterByStoreID(id) + } + + logger.Infof(ctx, "Deleted vector store: tenant=%d, id=%s", tenantID, id) + return nil } // SaveDetectedVersion updates the connection_config.version for a stored vector store. @@ -91,6 +119,28 @@ func (s *vectorStoreService) SaveDetectedVersion(ctx context.Context, store *typ return s.repo.UpdateConnectionConfig(ctx, &updated) } +// registerInRegistry creates an engine service and registers it in the registry. +// Logs and skips on failure — the store is already persisted in DB, +// and will be loaded on next app restart (self-healing). +func (s *vectorStoreService) registerInRegistry(ctx context.Context, store *types.VectorStore) { + if s.storeRegistry == nil || s.factory == nil { + return + } + + // Use a short timeout for engine creation to avoid blocking on unreachable hosts + // (e.g., gRPC dial to Qdrant/Milvus). The store is already persisted in DB, + // so it will be loaded on next app restart if this times out. + factoryCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + svc, err := s.factory(factoryCtx, *store) + if err != nil { + logger.Warnf(ctx, "Failed to create engine for store %s, will be available after restart: %v", store.ID, err) + return + } + s.storeRegistry.RegisterWithStoreID(store.ID, svc) +} + // validateConnectionConfig validates required fields per engine type. func validateConnectionConfig(engineType types.RetrieverEngineType, config types.ConnectionConfig) error { switch engineType { diff --git a/internal/application/service/vectorstore_test.go b/internal/application/service/vectorstore_test.go index 00cd5c17..41fc47b9 100644 --- a/internal/application/service/vectorstore_test.go +++ b/internal/application/service/vectorstore_test.go @@ -5,7 +5,9 @@ import ( "testing" "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/models/embedding" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -71,13 +73,88 @@ func (m *mockVectorStoreRepo) ExistsByEndpointAndIndex( return m.existsByEndpoint, nil } +// --------------------------------------------------------------------------- +// Mock StoreRegistry +// --------------------------------------------------------------------------- + +type mockStoreRegistry struct { + registered map[string]bool + unregistered []string +} + +func newMockStoreRegistry() *mockStoreRegistry { + return &mockStoreRegistry{registered: make(map[string]bool)} +} + +func (m *mockStoreRegistry) RegisterWithStoreID(storeID string, _ interfaces.RetrieveEngineService) { + m.registered[storeID] = true +} + +func (m *mockStoreRegistry) GetByStoreID(storeID string) (interfaces.RetrieveEngineService, error) { + return nil, nil +} + +func (m *mockStoreRegistry) UnregisterByStoreID(storeID string) { + m.unregistered = append(m.unregistered, storeID) + delete(m.registered, storeID) +} + +// --------------------------------------------------------------------------- +// Mock EngineFactory +// --------------------------------------------------------------------------- + +func mockEngineFactory(err error) interfaces.EngineFactory { + return func(_ context.Context, _ types.VectorStore) (interfaces.RetrieveEngineService, error) { + if err != nil { + return nil, err + } + return &mockEngineService{}, nil + } +} + +// mockEngineService satisfies interfaces.RetrieveEngineService minimally. +type mockEngineService struct{} + +func (m *mockEngineService) EngineType() types.RetrieverEngineType { return "mock" } +func (m *mockEngineService) Retrieve(_ context.Context, _ types.RetrieveParams) ([]*types.RetrieveResult, error) { + return nil, nil +} +func (m *mockEngineService) Support() []types.RetrieverType { return nil } +func (m *mockEngineService) Index(_ context.Context, _ embedding.Embedder, _ *types.IndexInfo, _ []types.RetrieverType) error { + return nil +} +func (m *mockEngineService) BatchIndex(_ context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) error { + return nil +} +func (m *mockEngineService) EstimateStorageSize(_ context.Context, _ embedding.Embedder, _ []*types.IndexInfo, _ []types.RetrieverType) int64 { + return 0 +} +func (m *mockEngineService) CopyIndices(_ context.Context, _ string, _ map[string]string, _ map[string]string, _ string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteByChunkIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteBySourceIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) DeleteByKnowledgeIDList(_ context.Context, _ []string, _ int, _ string) error { + return nil +} +func (m *mockEngineService) BatchUpdateChunkEnabledStatus(_ context.Context, _ map[string]bool) error { + return nil +} +func (m *mockEngineService) BatchUpdateChunkTagID(_ context.Context, _ map[string]string) error { + return nil +} + // --------------------------------------------------------------------------- // CreateStore tests // --------------------------------------------------------------------------- func TestCreateStore_Success(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -95,7 +172,7 @@ func TestCreateStore_Success(t *testing.T) { func TestCreateStore_ValidationError(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) tests := []struct { name string @@ -127,7 +204,7 @@ func TestCreateStore_ValidationError(t *testing.T) { func TestCreateStore_ConnectionConfigValidation(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) tests := []struct { name string @@ -213,7 +290,7 @@ func TestCreateStore_ConnectionConfigValidation(t *testing.T) { func TestCreateStore_DuplicateCheck_DBStore(t *testing.T) { repo := &mockVectorStoreRepo{existsByEndpoint: true} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -236,7 +313,7 @@ func TestCreateStore_DuplicateCheck_DBError(t *testing.T) { repo := &mockVectorStoreRepo{ existsByEndpointErr: assert.AnError, } - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -260,7 +337,7 @@ func TestCreateStore_DuplicateCheck_EnvStore(t *testing.T) { t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default") repo := &mockVectorStoreRepo{existsByEndpoint: false} // no DB duplicate - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -290,7 +367,7 @@ func TestCreateStore_DuplicateCheck_EnvStore_DifferentIndex_Allowed(t *testing.T t.Setenv("ELASTICSEARCH_INDEX", "xwrag_default") repo := &mockVectorStoreRepo{existsByEndpoint: false} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -310,7 +387,7 @@ func TestCreateStore_DuplicateCheck_EnvStore_DifferentIndex_Allowed(t *testing.T func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) { repo := &mockVectorStoreRepo{existsByEndpoint: false} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ TenantID: 1, @@ -328,13 +405,125 @@ func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) { assert.NoError(t, err) } +// --------------------------------------------------------------------------- +// CreateStore + Registry integration tests +// --------------------------------------------------------------------------- + +func TestCreateStore_RegistersInRegistry(t *testing.T) { + repo := &mockVectorStoreRepo{} + registry := newMockStoreRegistry() + factory := mockEngineFactory(nil) + svc := NewVectorStoreService(repo, registry, factory) + + store := &types.VectorStore{ + TenantID: 1, + Name: "test-es", + EngineType: types.ElasticsearchRetrieverEngineType, + ConnectionConfig: types.ConnectionConfig{ + Addr: "http://es:9200", + }, + } + + err := svc.CreateStore(context.Background(), store) + require.NoError(t, err) + + // Store should be persisted AND registered in registry + assert.Len(t, repo.stores, 1) + assert.True(t, registry.registered[store.ID]) +} + +func TestCreateStore_RegistryFailureDoesNotRollBackDB(t *testing.T) { + repo := &mockVectorStoreRepo{} + registry := newMockStoreRegistry() + factory := mockEngineFactory(assert.AnError) // factory fails + svc := NewVectorStoreService(repo, registry, factory) + + store := &types.VectorStore{ + TenantID: 1, + Name: "test-es", + EngineType: types.ElasticsearchRetrieverEngineType, + ConnectionConfig: types.ConnectionConfig{ + Addr: "http://es:9200", + }, + } + + // CreateStore should succeed even if registry fails (best-effort + self-healing) + err := svc.CreateStore(context.Background(), store) + assert.NoError(t, err) + + // DB should have the store + assert.Len(t, repo.stores, 1) + // Registry should NOT have it (factory failed) + assert.False(t, registry.registered[store.ID]) +} + +func TestCreateStore_NilRegistryAndFactory(t *testing.T) { + repo := &mockVectorStoreRepo{} + svc := NewVectorStoreService(repo, nil, nil) // no registry + + store := &types.VectorStore{ + TenantID: 1, + Name: "test-es", + EngineType: types.ElasticsearchRetrieverEngineType, + ConnectionConfig: types.ConnectionConfig{ + Addr: "http://es:9200", + }, + } + + // Should work fine without registry (degrades gracefully) + err := svc.CreateStore(context.Background(), store) + assert.NoError(t, err) + assert.Len(t, repo.stores, 1) +} + +// --------------------------------------------------------------------------- +// DeleteStore + Registry integration tests +// --------------------------------------------------------------------------- + +func TestDeleteStore_UnregistersFromRegistry(t *testing.T) { + repo := &mockVectorStoreRepo{} + registry := newMockStoreRegistry() + registry.registered["store-1"] = true + svc := NewVectorStoreService(repo, registry, nil) + + err := svc.DeleteStore(context.Background(), 1, "store-1") + require.NoError(t, err) + + // Should be unregistered + assert.Contains(t, registry.unregistered, "store-1") + assert.False(t, registry.registered["store-1"]) +} + +func TestDeleteStore_NilRegistryGraceful(t *testing.T) { + repo := &mockVectorStoreRepo{} + svc := NewVectorStoreService(repo, nil, nil) + + // Should not panic with nil registry + err := svc.DeleteStore(context.Background(), 1, "store-1") + assert.NoError(t, err) +} + +func TestDeleteStore_RepoErrorSkipsUnregister(t *testing.T) { + repo := &mockVectorStoreRepo{deleteErr: assert.AnError} + registry := newMockStoreRegistry() + registry.registered["store-1"] = true + svc := NewVectorStoreService(repo, registry, nil) + + err := svc.DeleteStore(context.Background(), 1, "store-1") + assert.Error(t, err) + + // Registry should NOT be touched if DB delete fails + assert.True(t, registry.registered["store-1"]) + assert.Empty(t, registry.unregistered) +} + // --------------------------------------------------------------------------- // UpdateStore tests // --------------------------------------------------------------------------- func TestUpdateStore_Success(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) store := &types.VectorStore{ ID: "test-id", @@ -348,7 +537,7 @@ func TestUpdateStore_Success(t *testing.T) { func TestUpdateStore_ValidationError(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) tests := []struct { name string @@ -378,7 +567,7 @@ func TestUpdateStore_ValidationError(t *testing.T) { func TestDeleteStore_Success(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) err := svc.DeleteStore(context.Background(), 1, "test-id") assert.NoError(t, err) @@ -386,19 +575,63 @@ func TestDeleteStore_Success(t *testing.T) { func TestDeleteStore_RepoError(t *testing.T) { repo := &mockVectorStoreRepo{deleteErr: assert.AnError} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) err := svc.DeleteStore(context.Background(), 1, "test-id") assert.Error(t, err) } +// --------------------------------------------------------------------------- +// SaveDetectedVersion tests +// --------------------------------------------------------------------------- + +func TestSaveDetectedVersion_Success(t *testing.T) { + repo := &mockVectorStoreRepo{} + svc := NewVectorStoreService(repo, nil, nil) + + store := &types.VectorStore{ + ID: "store-1", + TenantID: 1, + ConnectionConfig: types.ConnectionConfig{Addr: "http://es:9200"}, + } + + err := svc.SaveDetectedVersion(context.Background(), store, "7.10.1") + assert.NoError(t, err) +} + +func TestSaveDetectedVersion_RepoError(t *testing.T) { + repo := &mockVectorStoreRepo{updateErr: assert.AnError} + svc := NewVectorStoreService(repo, nil, nil) + + store := &types.VectorStore{ID: "store-1", TenantID: 1} + err := svc.SaveDetectedVersion(context.Background(), store, "8.11.0") + assert.Error(t, err) +} + +func TestSaveDetectedVersion_DoesNotMutateOriginal(t *testing.T) { + repo := &mockVectorStoreRepo{} + svc := NewVectorStoreService(repo, nil, nil) + + store := &types.VectorStore{ + ID: "store-1", + TenantID: 1, + ConnectionConfig: types.ConnectionConfig{Version: "old"}, + } + + err := svc.SaveDetectedVersion(context.Background(), store, "new") + require.NoError(t, err) + + // Original store must not be mutated + assert.Equal(t, "old", store.ConnectionConfig.Version) +} + // --------------------------------------------------------------------------- // TestConnection tests // --------------------------------------------------------------------------- func TestTestConnection_UnsupportedEngineType(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) _, err := svc.TestConnection(context.Background(), "unknown_engine", types.ConnectionConfig{}) require.Error(t, err) @@ -410,7 +643,7 @@ func TestTestConnection_UnsupportedEngineType(t *testing.T) { func TestTestConnection_SQLiteAlwaysSucceeds(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) version, err := svc.TestConnection(context.Background(), types.SQLiteRetrieverEngineType, types.ConnectionConfig{}) assert.NoError(t, err) @@ -419,7 +652,7 @@ func TestTestConnection_SQLiteAlwaysSucceeds(t *testing.T) { func TestTestConnection_PostgresDefaultConnection(t *testing.T) { repo := &mockVectorStoreRepo{} - svc := NewVectorStoreService(repo) + svc := NewVectorStoreService(repo, nil, nil) version, err := svc.TestConnection(context.Background(), types.PostgresRetrieverEngineType, types.ConnectionConfig{UseDefaultConnection: true}) diff --git a/internal/container/container.go b/internal/container/container.go index 7b75a6d4..af91c69a 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -191,6 +191,16 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(repository.NewVectorStoreRepository)) must(container.Provide(service.NewWebSearchService)) must(container.Provide(service.NewWebSearchProviderService)) + must(container.Provide(NewEngineFactory)) + // StoreRegistry: same instance as RetrieveEngineRegistry, exposed as StoreRegistry interface. + // NewRetrieveEngineRegistry always returns *retriever.RetrieveEngineRegistry which implements both. + must(container.Provide(func(r interfaces.RetrieveEngineRegistry) (interfaces.StoreRegistry, error) { + sr, ok := r.(*retriever.RetrieveEngineRegistry) + if !ok { + return nil, fmt.Errorf("registry does not implement StoreRegistry") + } + return sr, nil + })) must(container.Provide(service.NewVectorStoreService)) // Agent service layer (requires event bus, web search service) @@ -923,9 +933,43 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret } } } + // ─── DB store registration (byStoreID) ─── + if storeReg, ok := registry.(*retriever.RetrieveEngineRegistry); ok { + loadDBStoresIntoRegistry(storeReg, db, cfg) + } + return registry, nil } +// loadDBStoresIntoRegistry loads VectorStore records from DB and registers them +// in the registry's byStoreID map. Failures are logged and skipped (non-fatal). +func loadDBStoresIntoRegistry(storeRegistry interfaces.StoreRegistry, db *gorm.DB, cfg *config.Config) { + ctx := context.Background() + log := logger.GetLogger(ctx) + + var stores []types.VectorStore + // GORM soft delete automatically adds "deleted_at IS NULL" condition + if err := db.Find(&stores).Error; err != nil { + log.Warnf("Failed to load vector stores from DB: %v", err) + return + } + + if len(stores) == 0 { + return + } + + log.Infof("Loading %d vector store(s) from database", len(stores)) + for _, store := range stores { + svc, err := createEngineServiceFromStore(ctx, store, db, cfg) + if err != nil { + log.Errorf("Failed to create engine for store %s (%s): %v", store.ID, store.Name, err) + continue + } + storeRegistry.RegisterWithStoreID(store.ID, svc) + log.Infof("Registered DB vector store: id=%s, name=%s, engine=%s", store.ID, store.Name, store.EngineType) + } +} + // initAntsPool initializes the goroutine pool // Creates a managed goroutine pool for concurrent task execution // Parameters: diff --git a/internal/container/engine_factory.go b/internal/container/engine_factory.go new file mode 100644 index 00000000..e9eb4939 --- /dev/null +++ b/internal/container/engine_factory.go @@ -0,0 +1,205 @@ +package container + +import ( + "context" + "fmt" + "strings" + "time" + + esv7 "github.com/elastic/go-elasticsearch/v7" + "github.com/elastic/go-elasticsearch/v8" + "github.com/milvus-io/milvus/client/v2/milvusclient" + "github.com/qdrant/go-client/qdrant" + "github.com/weaviate/weaviate-go-client/v5/weaviate" + "github.com/weaviate/weaviate-go-client/v5/weaviate/auth" + wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc" + "google.golang.org/grpc" + "gorm.io/gorm" + + elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7" + elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8" + milvusRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/milvus" + postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres" + qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant" + sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite" + weaviateRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/weaviate" + "github.com/Tencent/WeKnora/internal/application/service/retriever" + "github.com/Tencent/WeKnora/internal/config" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// NewEngineFactory returns an EngineFactory function closed over db and cfg. +// Registered in dig and injected into VectorStoreService for dynamic registry updates. +func NewEngineFactory(db *gorm.DB, cfg *config.Config) interfaces.EngineFactory { + return func(ctx context.Context, store types.VectorStore) (interfaces.RetrieveEngineService, error) { + return createEngineServiceFromStore(ctx, store, db, cfg) + } +} + +// createEngineServiceFromStore creates a RetrieveEngineService from a VectorStore's config. +// This is the DB store counterpart of the env-based initialization in initRetrieveEngineRegistry. +func createEngineServiceFromStore( + ctx context.Context, + store types.VectorStore, + db *gorm.DB, + cfg *config.Config, +) (interfaces.RetrieveEngineService, error) { + switch store.EngineType { + case types.PostgresRetrieverEngineType: + return createPostgresEngine(store, db) + case types.ElasticsearchRetrieverEngineType: + return createElasticsearchEngine(store, cfg) + case types.QdrantRetrieverEngineType: + return createQdrantEngine(store) + case types.MilvusRetrieverEngineType: + return createMilvusEngine(ctx, store) + case types.WeaviateRetrieverEngineType: + return createWeaviateEngine(store) + case types.SQLiteRetrieverEngineType: + return createSQLiteEngine(store, db) + default: + return nil, fmt.Errorf("unsupported engine type: %s", store.EngineType) + } +} + +func createPostgresEngine(store types.VectorStore, db *gorm.DB) (interfaces.RetrieveEngineService, error) { + if store.ConnectionConfig.UseDefaultConnection { + repo := postgresRepo.NewPostgresRetrieveEngineRepository(db) + return retriever.NewKVHybridRetrieveEngine(repo, types.PostgresRetrieverEngineType), nil + } + // Phase 1: only UseDefaultConnection is supported. + // Custom connections require connection pool management and migration handling. + return nil, fmt.Errorf("custom postgres connections not yet supported; use use_default_connection=true") +} + +func createSQLiteEngine(_ types.VectorStore, db *gorm.DB) (interfaces.RetrieveEngineService, error) { + repo := sqliteRetrieverRepo.NewSQLiteRetrieveEngineRepository(db) + return retriever.NewKVHybridRetrieveEngine(repo, types.SQLiteRetrieverEngineType), nil +} + +func createElasticsearchEngine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig + // Version-based v7/v8 SDK selection. + // Version is auto-detected by PR2's TestConnection and saved to connection_config. + // Empty version defaults to v8 (latest SDK). + if isESv7(cc.Version) { + return createElasticsearchV7Engine(cc, cfg) + } + return createElasticsearchV8Engine(cc, cfg) +} + +// isESv7 checks if the detected ES version is 7.x. +func isESv7(version string) bool { + return strings.HasPrefix(version, "7.") +} + +func createElasticsearchV8Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) { + client, err := elasticsearch.NewTypedClient(elasticsearch.Config{ + Addresses: []string{cc.Addr}, + Username: cc.Username, + Password: cc.Password, + }) + if err != nil { + return nil, fmt.Errorf("create elasticsearch v8 client: %w", err) + } + repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg) + return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil +} + +func createElasticsearchV7Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) { + client, err := esv7.NewClient(esv7.Config{ + Addresses: []string{cc.Addr}, + Username: cc.Username, + Password: cc.Password, + }) + if err != nil { + return nil, fmt.Errorf("create elasticsearch v7 client: %w", err) + } + repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg) + return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil +} + +func createQdrantEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig + port := cc.Port + if port == 0 { + port = 6334 + } + + client, err := qdrant.NewClient(&qdrant.Config{ + Host: cc.Host, + Port: port, + APIKey: cc.APIKey, + UseTLS: cc.UseTLS, + }) + if err != nil { + return nil, fmt.Errorf("create qdrant client: %w", err) + } + repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client) + return retriever.NewKVHybridRetrieveEngine(repo, types.QdrantRetrieverEngineType), nil +} + +func createMilvusEngine(ctx context.Context, store types.VectorStore) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig + addr := cc.Addr + if addr == "" { + addr = "localhost:19530" + } + + milvusCfg := milvusclient.ClientConfig{ + Address: addr, + DialOptions: []grpc.DialOption{grpc.WithTimeout(5 * time.Second)}, + } + if cc.Username != "" { + milvusCfg.Username = cc.Username + } + if cc.Password != "" { + milvusCfg.Password = cc.Password + } + // NOTE: Milvus DBName is not yet in ConnectionConfig. + // Phase 1 limitation — only the default database is used. + + client, err := milvusclient.New(ctx, &milvusCfg) + if err != nil { + return nil, fmt.Errorf("create milvus client: %w", err) + } + repo := milvusRepo.NewMilvusRetrieveEngineRepository(client) + return retriever.NewKVHybridRetrieveEngine(repo, types.MilvusRetrieverEngineType), nil +} + +func createWeaviateEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig + host := cc.Host + if host == "" { + host = "weaviate:8080" + } + grpcAddress := cc.GrpcAddress + if grpcAddress == "" { + grpcAddress = "weaviate:50051" + } + scheme := cc.Scheme + if scheme == "" { + scheme = "http" + } + + weaviateCfg := weaviate.Config{ + Host: host, + GrpcConfig: &wgrpc.Config{ + Host: grpcAddress, + }, + Scheme: scheme, + } + // Unlike the env path (which checks WEAVIATE_AUTH_ENABLED), the factory uses + // APIKey directly — if a user provides it, they intend to use it. + if cc.APIKey != "" { + weaviateCfg.AuthConfig = auth.ApiKey{Value: cc.APIKey} + } + + client, err := weaviate.NewClient(weaviateCfg) + if err != nil { + return nil, fmt.Errorf("create weaviate client: %w", err) + } + repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client) + return retriever.NewKVHybridRetrieveEngine(repo, types.WeaviateRetrieverEngineType), nil +} diff --git a/internal/types/interfaces/vectorstore.go b/internal/types/interfaces/vectorstore.go index 5eca6990..d8513087 100644 --- a/internal/types/interfaces/vectorstore.go +++ b/internal/types/interfaces/vectorstore.go @@ -6,6 +6,23 @@ import ( "github.com/Tencent/WeKnora/internal/types" ) +// StoreRegistry provides VectorStore-based engine registration/lookup. +// Separated from RetrieveEngineRegistry to avoid changing the existing interface +// used by 6 services (17 call sites). Phase 2 may merge into RetrieveEngineRegistry. +type StoreRegistry interface { + // RegisterWithStoreID registers an engine service by VectorStore ID. + // Upsert semantics: existing entry is overwritten silently. + RegisterWithStoreID(storeID string, svc RetrieveEngineService) + // GetByStoreID retrieves an engine service by VectorStore ID. + GetByStoreID(storeID string) (RetrieveEngineService, error) + // UnregisterByStoreID removes an engine service by VectorStore ID (idempotent). + UnregisterByStoreID(storeID string) +} + +// EngineFactory creates a RetrieveEngineService from a VectorStore's config. +// Defined as a function type to avoid circular imports between container and service packages. +type EngineFactory func(ctx context.Context, store types.VectorStore) (RetrieveEngineService, error) + // VectorStoreService defines the service interface for vector store management. // Tenant isolation is enforced by the handler layer (getOwnedStore pattern). type VectorStoreService interface { From d546406a1541f8ab709ec1217478caf76b319fbf Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 16 Apr 2026 23:25:25 +0800 Subject: [PATCH 018/192] feat(output): enhance output formatting to XML for various tools - Updated the formatKnowledgeBaseList function to return knowledge base information as XML, improving data structure for integration. - Modified the formatOutput function in GrepChunksTool to format search results as XML, enhancing readability and consistency. - Adjusted the formatOutput method in KnowledgeSearchTool to output search results in XML format, providing a structured response. - Refactored the buildOutput function in ListKnowledgeChunksTool to generate XML output, improving the clarity of chunk information. These changes standardize output formats across multiple tools, facilitating better data handling and integration. --- internal/agent/prompts.go | 71 ++++--- internal/agent/tools/grep_chunks.go | 47 ++--- internal/agent/tools/knowledge_search.go | 174 +++++++----------- internal/agent/tools/list_knowledge_chunks.go | 76 ++++---- 4 files changed, 161 insertions(+), 207 deletions(-) diff --git a/internal/agent/prompts.go b/internal/agent/prompts.go index fd1eaabd..06960a69 100644 --- a/internal/agent/prompts.go +++ b/internal/agent/prompts.go @@ -105,79 +105,74 @@ func AvailablePlaceholders() []PlaceholderDefinition { return result } -// formatKnowledgeBaseList formats knowledge base information for the prompt +// formatKnowledgeBaseList formats knowledge base information as XML for the prompt func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string { if len(kbInfos) == 0 { - return "None" + return "" } - var builder strings.Builder - builder.WriteString("\nThe following knowledge bases have been selected by the user for this conversation. ") - builder.WriteString("You should search within these knowledge bases to find relevant information.\n\n") - for i, kb := range kbInfos { - // Display knowledge base name and ID - builder.WriteString(fmt.Sprintf("%d. **%s** (knowledge_base_id: `%s`)\n", i+1, kb.Name, kb.ID)) - - // Display knowledge base type + var b strings.Builder + b.WriteString("\n") + for _, kb := range kbInfos { kbType := kb.Type if kbType == "" { - kbType = "document" // Default type + kbType = "document" } - builder.WriteString(fmt.Sprintf(" - Type: %s\n", kbType)) - + b.WriteString(fmt.Sprintf("\n", + kb.ID, kb.Name, kbType, kb.DocCount)) if kb.Description != "" { - builder.WriteString(fmt.Sprintf(" - Description: %s\n", kb.Description)) + b.WriteString(fmt.Sprintf("%s\n", kb.Description)) } - builder.WriteString(fmt.Sprintf(" - Document count: %d\n", kb.DocCount)) - // Display recent documents if available - // For FAQ type knowledge bases, adjust the display format if len(kb.RecentDocs) > 0 { if kbType == "faq" { - // FAQ knowledge base: show Q&A pairs in a more compact format - builder.WriteString(" - Recent FAQ entries:\n\n") - builder.WriteString(" | # | Question | Answers | Chunk ID | Knowledge ID | Created At |\n") - builder.WriteString(" |---|-------------------|---------|----------|--------------|------------|\n") + b.WriteString("\n") for j, doc := range kb.RecentDocs { - if j >= 10 { // Limit to 10 documents + if j >= 10 { break } question := doc.FAQStandardQuestion if question == "" { question = doc.FileName } - answers := "-" + b.WriteString(fmt.Sprintf("\n", + doc.ChunkID, doc.KnowledgeID, doc.CreatedAt)) + b.WriteString(fmt.Sprintf("%s\n", question)) if len(doc.FAQAnswers) > 0 { - answers = strings.Join(doc.FAQAnswers, " | ") + for _, ans := range doc.FAQAnswers { + b.WriteString(fmt.Sprintf("%s\n", ans)) + } } - builder.WriteString(fmt.Sprintf(" | %d | %s | %s | `%s` | `%s` | %s |\n", - j+1, question, answers, doc.ChunkID, doc.KnowledgeID, doc.CreatedAt)) + b.WriteString("\n") } + b.WriteString("\n") } else { - // Document knowledge base: show documents in standard format - builder.WriteString(" - Recently added documents:\n\n") - builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n") - builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n") + b.WriteString("\n") for j, doc := range kb.RecentDocs { - if j >= 10 { // Limit to 10 documents + if j >= 10 { break } docName := doc.Title if docName == "" { docName = doc.FileName } - // Format file size fileSize := formatFileSize(doc.FileSize) - summary := formatDocSummary(doc.Description, 120) - builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n", - j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary)) + b.WriteString(fmt.Sprintf("\n", + doc.KnowledgeID, doc.Type, fileSize, doc.CreatedAt)) + b.WriteString(fmt.Sprintf("%s\n", docName)) + if doc.Description != "" { + summary := formatDocSummary(doc.Description, 120) + b.WriteString(fmt.Sprintf("%s\n", summary)) + } + b.WriteString("\n") } + b.WriteString("\n") } - builder.WriteString("\n") } - builder.WriteString("\n") + b.WriteString("\n") } - return builder.String() + b.WriteString("") + return b.String() } // renderPromptPlaceholders renders placeholders in the prompt template diff --git a/internal/agent/tools/grep_chunks.go b/internal/agent/tools/grep_chunks.go index 8fd2fda2..4637d7f5 100644 --- a/internal/agent/tools/grep_chunks.go +++ b/internal/agent/tools/grep_chunks.go @@ -374,7 +374,7 @@ func (t *GrepChunksTool) searchChunks( return results, int64(len(results)), nil } -// formatOutput formats the search results for display (grep-style output) +// formatOutput formats the search results as XML func (t *GrepChunksTool) formatOutput( ctx context.Context, results []knowledgeAggregation, @@ -382,46 +382,37 @@ func (t *GrepChunksTool) formatOutput( patterns []string, countOnly bool, ) string { - var output strings.Builder + var b strings.Builder - // If count_only mode, just return the count if countOnly { - output.WriteString(fmt.Sprintf("%d\n", totalCount)) - return output.String() + b.WriteString(fmt.Sprintf("\n", totalCount)) + return b.String() } - // Show search info - if len(patterns) == 1 { - output.WriteString(fmt.Sprintf("Pattern: '%s' (case-insensitive)\n", patterns[0])) - } else { - output.WriteString(fmt.Sprintf("Patterns (%d): %v (case-insensitive, OR logic)\n", len(patterns), patterns)) + b.WriteString(fmt.Sprintf("\n", len(results))) + for _, p := range patterns { + b.WriteString(fmt.Sprintf("%s\n", p)) } - output.WriteString(fmt.Sprintf("Matches: %d knowledge item(s)\n\n", len(results))) if len(results) == 0 { - output.WriteString("No matches found.\n") - return output.String() + b.WriteString("") + return b.String() } - for idx, result := range results { - var patternSummaries []string + for _, result := range results { + b.WriteString(fmt.Sprintf("\n", + result.KnowledgeID, result.KnowledgeTitle, result.ChunkHitCount, result.TotalChunkCount)) for _, pattern := range patterns { count := result.PatternCounts[pattern] - patternSummaries = append(patternSummaries, fmt.Sprintf("%s=%d", pattern, count)) + if count > 0 { + b.WriteString(fmt.Sprintf("\n", pattern, count)) + } } - - output.WriteString( - fmt.Sprintf("%d) knowledge_id=%s | title=%s | chunk_hits=%d | chunk_total=%d | pattern_hits=[%s]\n", - idx+1, - result.KnowledgeID, - result.KnowledgeTitle, - result.ChunkHitCount, - result.TotalChunkCount, - strings.Join(patternSummaries, ", "), - ), - ) + b.WriteString("\n") } - return output.String() + + b.WriteString("") + return b.String() } type knowledgeAggregation struct { diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.go index 22c657c7..412d9490 100644 --- a/internal/agent/tools/knowledge_search.go +++ b/internal/agent/tools/knowledge_search.go @@ -395,6 +395,21 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args json.RawMessage) } } + // Enrich image info for search results (lazy-loaded from child image chunks) + if t.chunkService != nil && len(deduplicatedResults) > 0 { + byTenant := make(map[uint64][]*types.SearchResult) + for _, r := range deduplicatedResults { + tid := t.searchTargets.GetTenantIDForKB(r.KnowledgeBaseID) + if tid == 0 { + continue + } + byTenant[tid] = append(byTenant[tid], r.SearchResult) + } + for tid, batch := range byTenant { + searchutil.EnrichSearchResultsImageInfo(ctx, t.chunkService.GetRepository(), tid, batch) + } + } + // Build output logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults)) result, err := t.formatOutput(ctx, deduplicatedResults, kbIDs, queries) @@ -1065,144 +1080,106 @@ func (t *KnowledgeSearchTool) formatOutput( }, nil } - // Build output header - output := "=== Search Results ===\n" - output += fmt.Sprintf("Found %d relevant results", len(results)) - output += "\n\n" - // Count results by KB kbCounts := make(map[string]int) for _, r := range results { kbCounts[r.KnowledgeID]++ } - output += "Knowledge Base Coverage:\n" - for kbID, count := range kbCounts { - output += fmt.Sprintf(" - %s: %d results\n", kbID, count) - } - output += "\n=== Detailed Results ===\n\n" + // Format individual results as XML + var ob strings.Builder + ob.WriteString(fmt.Sprintf("\n", len(results))) - // Format individual results formattedResults := make([]map[string]interface{}, 0, len(results)) - currentKB := "" faqMetadataCache := make(map[string]*types.FAQChunkMetadata) - // Track chunks per knowledge for statistics - knowledgeChunkMap := make(map[string]map[int]bool) // knowledge_id -> set of chunk_index - knowledgeTotalMap := make(map[string]int64) // knowledge_id -> total chunks - knowledgeTitleMap := make(map[string]string) // knowledge_id -> title + knowledgeChunkMap := make(map[string]map[int]bool) + knowledgeTotalMap := make(map[string]int64) + knowledgeTitleMap := make(map[string]string) for i, result := range results { var faqMeta *types.FAQChunkMetadata if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ { meta, err := t.getFAQMetadata(ctx, result.ID, faqMetadataCache) if err != nil { - logger.Warnf( - ctx, - "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v", - result.ID, - err, - ) + logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v", result.ID, err) } else { faqMeta = meta } } - // Track chunk indices per knowledge if knowledgeChunkMap[result.KnowledgeID] == nil { knowledgeChunkMap[result.KnowledgeID] = make(map[int]bool) } knowledgeChunkMap[result.KnowledgeID][result.ChunkIndex] = true knowledgeTitleMap[result.KnowledgeID] = result.KnowledgeTitle - // Group by knowledge base - if result.KnowledgeID != currentKB { - currentKB = result.KnowledgeID - if i > 0 { - output += "\n" - } - output += fmt.Sprintf("[Source Document: %s]\n", result.KnowledgeTitle) - - // Get total chunk count for this knowledge (cache it) - // Use KB's tenant_id from searchTargets to support cross-tenant shared KB - if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists { - // Get tenant_id from searchTargets using the KB ID from the result - effectiveTenantID := t.searchTargets.GetTenantIDForKB(result.KnowledgeBaseID) - if effectiveTenantID == 0 { - logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID) + // Cache total chunk count per knowledge + if _, exists := knowledgeTotalMap[result.KnowledgeID]; !exists { + effectiveTenantID := t.searchTargets.GetTenantIDForKB(result.KnowledgeBaseID) + if effectiveTenantID == 0 { + logger.Warnf(ctx, "[Tool][KnowledgeSearch] KB %s not found in searchTargets, skipping chunk count", result.KnowledgeBaseID) + knowledgeTotalMap[result.KnowledgeID] = 0 + } else { + _, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx, + effectiveTenantID, result.KnowledgeID, + &types.Pagination{Page: 1, PageSize: 1}, + []types.ChunkType{types.ChunkTypeText}, "", "", "", "", "", + ) + if err != nil { + logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v", result.KnowledgeID, err) knowledgeTotalMap[result.KnowledgeID] = 0 } else { - _, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx, - effectiveTenantID, result.KnowledgeID, - &types.Pagination{Page: 1, PageSize: 1}, - []types.ChunkType{types.ChunkTypeText}, "", "", "", "", "", - ) - if err != nil { - logger.Warnf( - ctx, - "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v", - result.KnowledgeID, - err, - ) - knowledgeTotalMap[result.KnowledgeID] = 0 - } else { - knowledgeTotalMap[result.KnowledgeID] = total - } + knowledgeTotalMap[result.KnowledgeID] = total } } } - // relevanceLevel := GetRelevanceLevel(result.Score) - output += fmt.Sprintf("\nResult #%d:\n", i+1) - output += fmt.Sprintf( - " [chunk_id: %s][chunk_index: %d]\nContent: %s\n", - result.ID, - result.ChunkIndex, - result.Content, - ) + ob.WriteString(fmt.Sprintf("\n", + i+1, result.ID, result.ChunkIndex, result.KnowledgeID, result.KnowledgeTitle)) + ob.WriteString(fmt.Sprintf("%s\n", result.Content)) - // 解析并输出关联的图片信息 if result.ImageInfo != "" { var imageInfos []types.ImageInfo if err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos); err == nil && len(imageInfos) > 0 { - output += fmt.Sprintf(" Related Images (%d):\n", len(imageInfos)) - for imgIdx, img := range imageInfos { - output += fmt.Sprintf(" Image %d:\n", imgIdx+1) - if img.URL != "" { - output += fmt.Sprintf(" URL: %s\n", img.URL) - } + for _, img := range imageInfos { + ob.WriteString(fmt.Sprintf("\n", img.URL)) if img.Caption != "" { - output += fmt.Sprintf(" Caption: %s\n", img.Caption) + ob.WriteString(fmt.Sprintf("%s\n", img.Caption)) } if img.OCRText != "" { - output += fmt.Sprintf(" OCR Text: %s\n", img.OCRText) + ob.WriteString(fmt.Sprintf("%s\n", img.OCRText)) } + ob.WriteString("\n") } } } if faqMeta != nil { + ob.WriteString("\n") if faqMeta.StandardQuestion != "" { - output += fmt.Sprintf(" FAQ Standard Question: %s\n", faqMeta.StandardQuestion) + ob.WriteString(fmt.Sprintf("%s\n", faqMeta.StandardQuestion)) } if len(faqMeta.SimilarQuestions) > 0 { - output += fmt.Sprintf(" FAQ Similar Questions: %s\n", strings.Join(faqMeta.SimilarQuestions, "; ")) - } - if len(faqMeta.Answers) > 0 { - output += " FAQ Answers:\n" - for ansIdx, ans := range faqMeta.Answers { - output += fmt.Sprintf(" Answer Choice %d: %s\n", ansIdx+1, ans) + for _, sq := range faqMeta.SimilarQuestions { + ob.WriteString(fmt.Sprintf("%s\n", sq)) } } + if len(faqMeta.Answers) > 0 { + for _, ans := range faqMeta.Answers { + ob.WriteString(fmt.Sprintf("%s\n", ans)) + } + } + ob.WriteString("\n") } + ob.WriteString("\n") + formattedResults = append(formattedResults, map[string]interface{}{ - "result_index": i + 1, - "chunk_id": result.ID, - "content": result.Content, - // "score": result.Score, - // "relevance_level": relevanceLevel, + "result_index": i + 1, + "chunk_id": result.ID, + "content": result.Content, "knowledge_id": result.KnowledgeID, "knowledge_title": result.KnowledgeTitle, "match_type": result.MatchType, @@ -1213,11 +1190,9 @@ func (t *KnowledgeSearchTool) formatOutput( last := formattedResults[len(formattedResults)-1] - // 添加图片信息到结构化数据 if result.ImageInfo != "" { var imageInfos []types.ImageInfo if err := json.Unmarshal([]byte(result.ImageInfo), &imageInfos); err == nil && len(imageInfos) > 0 { - // 构建简化的图片信息列表 imageList := make([]map[string]string, 0, len(imageInfos)) for _, img := range imageInfos { imgData := make(map[string]string) @@ -1253,36 +1228,23 @@ func (t *KnowledgeSearchTool) formatOutput( } } - // Add statistics and recommendations for each knowledge - output += "\n=== Retrieval Statistics ===\n\n" + // Retrieval statistics + ob.WriteString("\n") for knowledgeID, retrievedChunks := range knowledgeChunkMap { totalChunks := knowledgeTotalMap[knowledgeID] retrievedCount := len(retrievedChunks) title := knowledgeTitleMap[knowledgeID] - if totalChunks > 0 { - percentage := float64(retrievedCount) / float64(totalChunks) * 100 remaining := totalChunks - int64(retrievedCount) - - output += fmt.Sprintf("Document: %s (%s)\n", title, knowledgeID) - output += fmt.Sprintf(" Total Chunks: %d\n", totalChunks) - output += fmt.Sprintf(" Retrieved: %d (%.1f%%)\n", retrievedCount, percentage) - output += fmt.Sprintf(" Remaining: %d\n", remaining) - + percentage := float64(retrievedCount) / float64(totalChunks) * 100 + ob.WriteString(fmt.Sprintf("\n", + knowledgeID, title, totalChunks, retrievedCount, remaining, percentage)) } } + ob.WriteString("\n") + ob.WriteString("") - // // Add usage guidance - // output += "\n\n=== Usage Guidelines ===\n" - // output += "- High relevance (>=0.8): directly usable for answering\n" - // output += "- Medium relevance (0.6-0.8): use as supplementary reference\n" - // output += "- Low relevance (<0.6): use with caution, may not be accurate\n" - // if totalBeforeFilter > len(results) { - // output += "- Results below threshold have been automatically filtered\n" - // } - // output += "- Full content is already included in search results above\n" - // output += "- Results are deduplicated across knowledge bases and sorted by relevance\n" - // output += "- Use list_knowledge_chunks to expand context if needed\n" + output := ob.String() data := map[string]interface{}{ "knowledge_base_ids": kbsToSearch, diff --git a/internal/agent/tools/list_knowledge_chunks.go b/internal/agent/tools/list_knowledge_chunks.go index 02e95ad5..13633ea2 100644 --- a/internal/agent/tools/list_knowledge_chunks.go +++ b/internal/agent/tools/list_knowledge_chunks.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/searchutil" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" ) @@ -160,6 +161,22 @@ func (t *ListKnowledgeChunksTool) Execute(ctx context.Context, args json.RawMess totalChunks := total fetched := len(chunks) + // Enrich image info from child image chunks (lazy loading) + if fetched > 0 { + chunkIDs := make([]string, 0, fetched) + for _, c := range chunks { + chunkIDs = append(chunkIDs, c.ID) + } + infoMap := searchutil.CollectImageInfoByChunkIDs(ctx, t.chunkService.GetRepository(), effectiveTenantID, chunkIDs) + for _, c := range chunks { + if c.ImageInfo == "" { + if merged, ok := infoMap[c.ID]; ok { + c.ImageInfo = merged + } + } + } + } + knowledgeTitle := t.lookupKnowledgeTitle(ctx, knowledgeID) output := t.buildOutput(knowledgeID, knowledgeTitle, totalChunks, fetched, chunks) @@ -236,7 +253,7 @@ func (t *ListKnowledgeChunksTool) lookupKnowledgeTitle(ctx context.Context, know return strings.TrimSpace(knowledge.Title) } -// buildOutput builds the output for the list knowledge chunks tool +// buildOutput builds the output as XML for the list knowledge chunks tool func (t *ListKnowledgeChunksTool) buildOutput( knowledgeID string, knowledgeTitle string, @@ -244,65 +261,54 @@ func (t *ListKnowledgeChunksTool) buildOutput( fetched int, chunks []*types.Chunk, ) string { - builder := &strings.Builder{} - builder.WriteString("=== Knowledge Document Chunks ===\n\n") + var b strings.Builder + titleAttr := "" if knowledgeTitle != "" { - fmt.Fprintf(builder, "Document: %s (%s)\n", knowledgeTitle, knowledgeID) - } else { - fmt.Fprintf(builder, "Document ID: %s\n", knowledgeID) + titleAttr = fmt.Sprintf(" title=\"%s\"", knowledgeTitle) } - fmt.Fprintf(builder, "Total chunks: %d\n", total) + fmt.Fprintf(&b, "\n", + knowledgeID, titleAttr, total, fetched) if fetched == 0 { - builder.WriteString("No chunks found. Please confirm the document has been parsed.\n") - if total > 0 { - builder.WriteString("Document exists but the current page is empty. Please check pagination parameters.\n") - } - return builder.String() + b.WriteString("") + return b.String() } - fmt.Fprintf( - builder, - "Fetched: %d chunks, range: %d - %d\n\n", - fetched, - chunks[0].ChunkIndex, - chunks[len(chunks)-1].ChunkIndex, - ) - builder.WriteString("=== Chunk Content Preview ===\n\n") - for idx, c := range chunks { - fmt.Fprintf(builder, "Chunk #%d (Index %d)\n", idx+1, c.ChunkIndex+1) - fmt.Fprintf(builder, " chunk_id: %s\n", c.ID) - fmt.Fprintf(builder, " Type: %s\n", c.ChunkType) - fmt.Fprintf(builder, " Content: %s\n", summarizeContent(c.Content)) + for _, c := range chunks { + fmt.Fprintf(&b, "\n", + c.ID, c.ChunkIndex, c.ChunkType) + fmt.Fprintf(&b, "%s\n", summarizeContent(c.Content)) - // Output associated image information if c.ImageInfo != "" { var imageInfos []types.ImageInfo if err := json.Unmarshal([]byte(c.ImageInfo), &imageInfos); err == nil && len(imageInfos) > 0 { - fmt.Fprintf(builder, " Associated images (%d):\n", len(imageInfos)) - for imgIdx, img := range imageInfos { - fmt.Fprintf(builder, " Image %d:\n", imgIdx+1) + for _, img := range imageInfos { if img.URL != "" { - fmt.Fprintf(builder, " URL: %s\n", img.URL) + fmt.Fprintf(&b, "\n", img.URL) + } else { + b.WriteString("\n") } if img.Caption != "" { - fmt.Fprintf(builder, " Caption: %s\n", img.Caption) + fmt.Fprintf(&b, "%s\n", img.Caption) } if img.OCRText != "" { - fmt.Fprintf(builder, " OCR Text: %s\n", img.OCRText) + fmt.Fprintf(&b, "%s\n", img.OCRText) } + b.WriteString("\n") } } } - builder.WriteString("\n") + + b.WriteString("\n") } if int64(fetched) < total { - builder.WriteString("Note: The document has more chunks. Adjust offset or make multiple calls to retrieve all content.\n") + fmt.Fprintf(&b, "\n", int64(total)-int64(fetched)) } - return builder.String() + b.WriteString("") + return b.String() } // summarizeContent summarizes the content of a chunk From 092044b68fafe7ada9a5fa25b4693530e306ed9e Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 17 Apr 2026 11:55:32 +0800 Subject: [PATCH 019/192] refactor(postgres): optimize vector retrieval and HNSW settings - Adjusted the expanded TopK limit to a maximum of 200 candidates to enhance HNSW efficiency. - Updated the vector retrieval query to ensure the ORDER BY expression matches the indexed expression, improving index usage. - Implemented local settings for HNSW's ef_search and iterative_scan within a transaction to optimize candidate retrieval. - Added fallback logic to handle unsupported GUCs gracefully, ensuring query execution continues even with older pgvector versions. These changes improve the performance and reliability of vector retrieval in the PostgreSQL implementation. --- .../retriever/postgres/repository.go | 90 +++++++++++++++---- .../service/chat_pipeline/merge_overlap.go | 30 ++++++- .../service/knowledgebase_search.go | 4 +- 3 files changed, 103 insertions(+), 21 deletions(-) diff --git a/internal/application/repository/retriever/postgres/repository.go b/internal/application/repository/retriever/postgres/repository.go index 5d26e591..f89b9463 100644 --- a/internal/application/repository/retriever/postgres/repository.go +++ b/internal/application/repository/retriever/postgres/repository.go @@ -193,13 +193,13 @@ func (g *pgRepository) KeywordsRetrieve(ctx context.Context, Values: common.ToInterfaceSlice(params.TagIDs), }) } - + // Use ParadeDB's ||| operator for matching any token conds = append(conds, clause.Expr{ SQL: "content ||| ?", Vars: []interface{}{params.Query}, }) - + // Filter by is_enabled = true or NULL (NULL means enabled for historical data) conds = append(conds, clause.Expr{ SQL: "(is_enabled IS NULL OR is_enabled = ?)", @@ -340,22 +340,36 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context, whereClause = "WHERE " + strings.Join(whereParts, " AND ") } - // Expand TopK to get more candidates before threshold filtering + // Expand TopK to get more candidates before threshold filtering. + // + // HNSW requires `ef_search >= LIMIT`, and a very large LIMIT (e.g. 1000) + // forces HNSW to walk a near-exhaustive portion of the graph, often making + // it slower than a sequential scan and pushing the planner to pick Seq Scan + // even when an index exists. 200 is a good sweet spot: it gives enough + // headroom for threshold/filter post-processing without ballooning ef_search. expandedTopK := params.TopK * 2 if expandedTopK < 100 { expandedTopK = 100 // Minimum 100 candidates } - if expandedTopK > 1000 { - expandedTopK = 1000 // Maximum 1000 candidates + if expandedTopK > 200 { + expandedTopK = 200 // Maximum 200 candidates (keeps HNSW efficient) } if expandedTopK < params.TopK { expandedTopK = params.TopK // Ensure subquery limit is at least final limit } - // Optimized query: Use subquery to calculate distance once - // Strategy: Use ORDER BY with vector distance to leverage HNSW index, - // then filter by threshold in outer query - // This allows PostgreSQL to use HNSW index efficiently + // Optimized query: Use subquery to calculate distance once. + // + // IMPORTANT: The HNSW index in this project is built on the EXPRESSION + // (embedding::halfvec()) halfvec_cosine_ops + // because the `embedding` column itself is `halfvec` without a fixed dimension + // (so the table can store multiple embedding sizes such as 798 / 3584 / ...). + // + // pgvector requires the ORDER BY expression to match the indexed expression + // EXACTLY, otherwise the planner falls back to a sequential scan. The + // `embedding::halfvec(%d)` cast on both sides of `<=>` is therefore NOT + // redundant — it is the only way to make the HNSW index get used at all. + // See: pgvector issues #702, #835 and ParadeDB "indexing-expressions" docs. subqueryLimitParam := len(allVars) + 1 thresholdParam := len(allVars) + 2 finalLimitParam := len(allVars) + 3 @@ -367,24 +381,66 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context, FROM ( SELECT id, content, source_id, source_type, chunk_id, knowledge_id, knowledge_base_id, tag_id, - embedding <=> $1::halfvec as distance + embedding::halfvec(%[1]d) <=> $1::halfvec(%[1]d) as distance FROM embeddings - %s - ORDER BY embedding <=> $1::halfvec - LIMIT $%d + %[2]s + ORDER BY embedding::halfvec(%[1]d) <=> $1::halfvec(%[1]d) + LIMIT $%[3]d ) AS candidates - WHERE distance <= $%d + WHERE distance <= $%[4]d ORDER BY distance ASC - LIMIT $%d - `, whereClause, subqueryLimitParam, thresholdParam, finalLimitParam) + LIMIT $%[5]d + `, dimension, whereClause, subqueryLimitParam, thresholdParam, finalLimitParam) allVars = append(allVars, expandedTopK) // LIMIT in subquery allVars = append(allVars, 1-params.Threshold) // Distance threshold allVars = append(allVars, params.TopK) // Final LIMIT + // HNSW's `ef_search` defaults to 40, which is much smaller than our + // `expandedTopK` budget (up to 1000). Without raising it, HNSW would only + // return ~40 candidates per scan and our outer threshold/filter step would + // silently lose recall. `SET LOCAL` requires a transaction so we wrap the + // query in one. We never write inside this transaction, so the cost is + // negligible. + efSearch := expandedTopK + if efSearch < 40 { + efSearch = 40 + } + var embeddingDBList []pgVectorWithScore - err := g.db.WithContext(ctx).Raw(querySQL, allVars...).Scan(&embeddingDBList).Error + err := g.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if err := tx.Exec(fmt.Sprintf("SET LOCAL hnsw.ef_search = %d", efSearch)).Error; err != nil { + // Treat as non-fatal: pgvector should always expose this GUC, but if + // for any reason it does not we still want the query to run (just + // with default recall). We must rollback first because a failed + // statement aborts the transaction in PostgreSQL. + logger.GetLogger(ctx).Warnf("[Postgres] Failed to set hnsw.ef_search=%d: %v", efSearch, err) + return err + } + // pgvector >= 0.8 supports iterative scan, which keeps pulling more + // candidates from HNSW until the post-filter (knowledge_base_id / + // knowledge_id / tag_id / is_enabled) yields enough rows. Without it, + // HNSW returns at most ef_search candidates and the outer filter may + // silently lose recall when the filter is selective. + // Best-effort: ignore failure on older pgvector versions. + if err := tx.Exec("SET LOCAL hnsw.iterative_scan = strict_order").Error; err != nil { + logger.GetLogger(ctx).Debugf("[Postgres] hnsw.iterative_scan not available: %v", err) + // abort transaction and let the fallback path below handle it. + return err + } + return tx.Raw(querySQL, allVars...).Scan(&embeddingDBList).Error + }) + + // Fallback: if the transaction failed because of an unsupported GUC (e.g. + // older pgvector that doesn't have hnsw.ef_search or hnsw.iterative_scan), + // retry the query without the SETs so we still return results. + if err != nil && len(embeddingDBList) == 0 && + (strings.Contains(err.Error(), "hnsw.ef_search") || + strings.Contains(err.Error(), "hnsw.iterative_scan")) { + logger.GetLogger(ctx).Warnf("[Postgres] Retrying vector query without HNSW GUC overrides: %v", err) + err = g.db.WithContext(ctx).Raw(querySQL, allVars...).Scan(&embeddingDBList).Error + } if err == gorm.ErrRecordNotFound { logger.GetLogger(ctx).Warnf("[Postgres] No vector matches found that meet threshold %.4f", params.Threshold) diff --git a/internal/application/service/chat_pipeline/merge_overlap.go b/internal/application/service/chat_pipeline/merge_overlap.go index ba27e6ec..009d11d3 100644 --- a/internal/application/service/chat_pipeline/merge_overlap.go +++ b/internal/application/service/chat_pipeline/merge_overlap.go @@ -30,10 +30,36 @@ func (p *PluginMerge) mergeOverlappingChunks( continue } - // Partial overlap: append the non-overlapping suffix + // Partial overlap: append the non-overlapping suffix. + // + // Offset math assumes len([]rune(Content)) == EndAt-StartAt, but a + // few upstream paths break that invariant: + // - Parent-child chunker prepends table headers, so Content may be + // longer than EndAt-StartAt. + // - Legacy data / mixed chunk sources may carry EndAt-StartAt that + // exceed the actual rune length of Content. + // We clamp offset into [0, len(contentRunes)] so the merge degrades + // gracefully instead of panicking with a negative slice bound. if chunks[i].EndAt > lastChunk.EndAt { contentRunes := []rune(chunks[i].Content) - offset := len(contentRunes) - (chunks[i].EndAt - lastChunk.EndAt) + suffixLen := chunks[i].EndAt - lastChunk.EndAt + offset := len(contentRunes) - suffixLen + if offset < 0 || offset > len(contentRunes) { + pipelineWarn(ctx, "Merge", "overlap_offset_clamp", map[string]interface{}{ + "knowledge_id": knowledgeID, + "chunk_id": chunks[i].ID, + "content_runes": len(contentRunes), + "chunk_start": chunks[i].StartAt, + "chunk_end": chunks[i].EndAt, + "last_end": lastChunk.EndAt, + "computed_offset": offset, + }) + if offset < 0 { + offset = 0 + } else { + offset = len(contentRunes) + } + } lastChunk.Content = lastChunk.Content + string(contentRunes[offset:]) lastChunk.EndAt = chunks[i].EndAt lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID) diff --git a/internal/application/service/knowledgebase_search.go b/internal/application/service/knowledgebase_search.go index d2717aa5..39d007f7 100644 --- a/internal/application/service/knowledgebase_search.go +++ b/internal/application/service/knowledgebase_search.go @@ -114,8 +114,8 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context, // Use 5x over-retrieval to ensure sufficient candidates for RRF fusion and reranking. // Scale proportionally when searching multiple KBs to maintain per-KB recall quality. matchCount := max(params.MatchCount*5, 50) * len(searchKBIDs) - if matchCount > 1000 { - matchCount = 1000 + if matchCount > 500 { + matchCount = 500 } // Build retrieval parameters for vector and keyword engines From 7bd36bf954cd943cc9ba6ae56746552c039ef438 Mon Sep 17 00:00:00 2001 From: hjz <1141520944@qq.com> Date: Wed, 15 Apr 2026 08:53:09 +0800 Subject: [PATCH 020/192] feat: search engine adds proxy addresses and adds SSRF verification. --- frontend/src/api/web-search-provider.ts | 2 + frontend/src/i18n/locales/en-US.ts | 3 + frontend/src/i18n/locales/ko-KR.ts | 3 + frontend/src/i18n/locales/ru-RU.ts | 3 + frontend/src/i18n/locales/zh-CN.ts | 3 + .../src/views/settings/WebSearchSettings.vue | 13 +++- internal/application/service/web_search.go | 17 +++- .../service/web_search_provider.go | 14 ++++ internal/infrastructure/web_search/bing.go | 5 +- .../infrastructure/web_search/duckduckgo.go | 12 +-- internal/infrastructure/web_search/google.go | 6 ++ internal/infrastructure/web_search/proxy.go | 68 ++++++++++++++++ .../infrastructure/web_search/proxy_test.go | 78 +++++++++++++++++++ internal/infrastructure/web_search/tavily.go | 5 +- internal/types/web_search.go | 1 + internal/types/web_search_provider.go | 9 +++ 16 files changed, 228 insertions(+), 14 deletions(-) create mode 100644 internal/infrastructure/web_search/proxy.go create mode 100644 internal/infrastructure/web_search/proxy_test.go diff --git a/frontend/src/api/web-search-provider.ts b/frontend/src/api/web-search-provider.ts index de203fb2..e315ce78 100644 --- a/frontend/src/api/web-search-provider.ts +++ b/frontend/src/api/web-search-provider.ts @@ -10,6 +10,7 @@ export interface WebSearchProviderEntity { parameters: { api_key?: string engine_id?: string + proxy_url?: string extra_config?: Record } is_default?: boolean @@ -23,6 +24,7 @@ export interface WebSearchProviderTypeInfo { name: string requires_api_key: boolean requires_engine_id?: boolean + supports_proxy?: boolean description?: string docs_url?: string } diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 8c95f99f..4bed7b8f 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -776,6 +776,9 @@ export default { providerLabel: 'Search Provider', providerDescription: 'Choose the search engine service used for web search', providerPlaceholder: 'Select a search engine...', + proxyUrlLabel: 'HTTP proxy', + proxyUrlPlaceholder: 'e.g. http://proxy.example.com:3128 (optional; http/https only)', + proxyUrlHelp: 'Use when outbound access to the search API requires a proxy; leave empty to rely on HTTP_PROXY/HTTPS_PROXY environment variables.', apiKeyLabel: 'API Key', apiKeyDescription: 'Enter the API key for the selected search provider', apiKeyPlaceholder: 'Enter API key', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index c52cb0b2..7071150c 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -636,6 +636,9 @@ export default { providerLabel: "검색 엔진 프로바이더", providerDescription: "웹 검색에 사용할 검색 엔진 서비스 선택", providerPlaceholder: "검색 엔진 선택...", + proxyUrlLabel: "HTTP 프록시", + proxyUrlPlaceholder: "예: http://127.0.0.1:7890 (선택 사항)", + proxyUrlHelp: "검색 API 접근에 프록시가 필요한 경우 입력합니다. 비우면 HTTP_PROXY/HTTPS_PROXY를 사용합니다.", apiKeyLabel: "API 키", apiKeyDescription: "선택한 검색 엔진의 API 키 입력", apiKeyPlaceholder: "API 키를 입력하세요", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 44ae3dd0..022f76e9 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -754,6 +754,9 @@ export default { providerLabel: 'Провайдер поиска', providerDescription: 'Выберите поисковый сервис, используемый для веб-поиска', providerPlaceholder: 'Выберите поисковую систему...', + proxyUrlLabel: 'HTTP-прокси', + proxyUrlPlaceholder: 'Напр. http://127.0.0.1:7890 (необязательно)', + proxyUrlHelp: 'Укажите, если доступ к API поиска нужен через прокси; иначе используются переменные HTTP_PROXY/HTTPS_PROXY.', apiKeyLabel: 'API-ключ', apiKeyDescription: 'Введите API-ключ выбранного провайдера поиска', apiKeyPlaceholder: 'Введите API-ключ', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 32ea5810..8a3180d1 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -636,6 +636,9 @@ export default { providerLabel: "搜索引擎提供商", providerDescription: "选择用于网络搜索的搜索引擎服务", providerPlaceholder: "选择搜索引擎...", + proxyUrlLabel: "HTTP 代理", + proxyUrlPlaceholder: "例如 http://proxy.example.com:3128(可选,仅支持 http/https)", + proxyUrlHelp: "若环境访问搜索 API 需代理,在此填写;留空则使用系统环境变量 HTTP(S)_PROXY。", apiKeyLabel: "API 密钥", apiKeyDescription: "输入所选搜索引擎的 API 密钥", apiKeyPlaceholder: "请输入 API 密钥", diff --git a/frontend/src/views/settings/WebSearchSettings.vue b/frontend/src/views/settings/WebSearchSettings.vue index 5301d777..7a5f6ff6 100644 --- a/frontend/src/views/settings/WebSearchSettings.vue +++ b/frontend/src/views/settings/WebSearchSettings.vue @@ -99,6 +99,16 @@ + + + + +
@@ -164,7 +174,7 @@ const providerForm = ref<{ name: string provider: string description: string - parameters: { api_key?: string; engine_id?: string } + parameters: { api_key?: string; engine_id?: string; proxy_url?: string } is_default: boolean }>({ name: '', @@ -228,6 +238,7 @@ const editProvider = (entity: WebSearchProviderEntity) => { parameters: { api_key: '', engine_id: entity.parameters?.engine_id || '', + proxy_url: entity.parameters?.proxy_url || '', }, is_default: entity.is_default || false, } diff --git a/internal/application/service/web_search.go b/internal/application/service/web_search.go index e41cc2bc..f4164480 100644 --- a/internal/application/service/web_search.go +++ b/internal/application/service/web_search.go @@ -105,7 +105,8 @@ func (s *WebSearchService) resolveProvider( return nil, fmt.Errorf("web search provider not found: %s", providerID) } - provider, err := s.registry.CreateProvider(string(entity.Provider), entity.Parameters) + params := mergeProxyFromWebSearchConfig(entity.Parameters, cfg) + provider, err := s.registry.CreateProvider(string(entity.Provider), params) if err != nil { return nil, fmt.Errorf("failed to create provider %s (%s): %w", entity.Name, entity.Provider, err) } @@ -115,9 +116,9 @@ func (s *WebSearchService) resolveProvider( // Backward compatibility: use the deprecated config.Provider field if cfg.Provider != "" { logger.Warnf(ctx, "Using deprecated WebSearchConfig.Provider field: %s. Please migrate to WebSearchProviderEntity.", cfg.Provider) - params := types.WebSearchProviderParameters{ + params := mergeProxyFromWebSearchConfig(types.WebSearchProviderParameters{ APIKey: cfg.APIKey, - } + }, cfg) provider, err := s.registry.CreateProvider(cfg.Provider, params) if err != nil { return nil, fmt.Errorf("web search provider %s is not available: %w", cfg.Provider, err) @@ -128,6 +129,16 @@ func (s *WebSearchService) resolveProvider( return nil, fmt.Errorf("no web search provider configured") } +// mergeProxyFromWebSearchConfig applies cfg.ProxyURL over stored provider params when non-empty (call-time override). +func mergeProxyFromWebSearchConfig(base types.WebSearchProviderParameters, cfg *types.WebSearchConfig) types.WebSearchProviderParameters { + if cfg != nil { + if pu := strings.TrimSpace(cfg.ProxyURL); pu != "" { + base.ProxyURL = pu + } + } + return base +} + // CompressWithRAG performs RAG-based compression using a temporary, hidden knowledge base. // The temporary knowledge base is deleted after use. The UI will not list it due to repo filtering. func (s *WebSearchService) CompressWithRAG( diff --git a/internal/application/service/web_search_provider.go b/internal/application/service/web_search_provider.go index f61ec899..c8a8fa68 100644 --- a/internal/application/service/web_search_provider.go +++ b/internal/application/service/web_search_provider.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -60,6 +61,12 @@ func (s *webSearchProviderService) UpdateProvider(ctx context.Context, provider } } + if provider.Provider != "" { + if err := validateProviderParameters(provider.Provider, provider.Parameters); err != nil { + return err + } + } + logger.Infof(ctx, "Updating web search provider: tenant=%d, id=%s", provider.TenantID, provider.ID) return s.repo.Update(ctx, provider) } @@ -114,5 +121,12 @@ func validateProviderParameters(provider types.WebSearchProviderType, params typ case types.WebSearchProviderTypeDuckDuckGo: // No API key required } + if err := validateOptionalProxyURL(params.ProxyURL); err != nil { + return err + } return nil } + +func validateOptionalProxyURL(proxyURL string) error { + return infra_web_search.ValidateProxyURL(proxyURL) +} diff --git a/internal/infrastructure/web_search/bing.go b/internal/infrastructure/web_search/bing.go index 68eab98e..b5ba35b4 100644 --- a/internal/infrastructure/web_search/bing.go +++ b/internal/infrastructure/web_search/bing.go @@ -54,8 +54,9 @@ func NewBingProvider(params types.WebSearchProviderParameters) (interfaces.WebSe if params.APIKey == "" { return nil, fmt.Errorf("API key is required for Bing provider") } - client := &http.Client{ - Timeout: defaultBingTimeout, + client, err := NewSearchHTTPClient(defaultBingTimeout, params.ProxyURL) + if err != nil { + return nil, err } return &BingProvider{ client: client, diff --git a/internal/infrastructure/web_search/duckduckgo.go b/internal/infrastructure/web_search/duckduckgo.go index 5a405c18..0eaa8db2 100644 --- a/internal/infrastructure/web_search/duckduckgo.go +++ b/internal/infrastructure/web_search/duckduckgo.go @@ -23,13 +23,13 @@ type DuckDuckGoProvider struct { } // NewDuckDuckGoProvider creates a new DuckDuckGo provider. -// DuckDuckGo is free and requires no API key or configuration. +// DuckDuckGo is free and requires no API key; optional ProxyURL tunnels requests via an HTTP/HTTPS proxy. func NewDuckDuckGoProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) { - return &DuckDuckGoProvider{ - client: &http.Client{ - Timeout: 30 * time.Second, - }, - }, nil + client, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL) + if err != nil { + return nil, err + } + return &DuckDuckGoProvider{client: client}, nil } // Name returns the provider name diff --git a/internal/infrastructure/web_search/google.go b/internal/infrastructure/web_search/google.go index af355676..2da39288 100644 --- a/internal/infrastructure/web_search/google.go +++ b/internal/infrastructure/web_search/google.go @@ -3,6 +3,7 @@ package web_search import ( "context" "fmt" + "time" "google.golang.org/api/customsearch/v1" "google.golang.org/api/option" @@ -29,8 +30,13 @@ func NewGoogleProvider(params types.WebSearchProviderParameters) (interfaces.Web return nil, fmt.Errorf("engine ID is required for Google provider") } + httpClient, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL) + if err != nil { + return nil, err + } clientOpts := []option.ClientOption{ option.WithAPIKey(params.APIKey), + option.WithHTTPClient(httpClient), } srv, err := customsearch.NewService(context.Background(), clientOpts...) if err != nil { diff --git a/internal/infrastructure/web_search/proxy.go b/internal/infrastructure/web_search/proxy.go new file mode 100644 index 00000000..d7bc0689 --- /dev/null +++ b/internal/infrastructure/web_search/proxy.go @@ -0,0 +1,68 @@ +package web_search + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/utils" +) + +// ValidateProxyURL delegates to utils.ValidateURLForSSRF (only http/https pass that check). +func ValidateProxyURL(proxyURL string) error { + proxyURL = strings.TrimSpace(proxyURL) + if proxyURL == "" { + return nil + } + return utils.ValidateURLForSSRF(proxyURL) +} + +func ssrfSafeRedirect(maxRedirects int) func(*http.Request, []*http.Request) error { + return func(req *http.Request, via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + if err := utils.ValidateURLForSSRF(req.URL.String()); err != nil { + return fmt.Errorf("%w: %v", utils.ErrSSRFRedirectBlocked, err) + } + return nil + } +} + +// NewSearchHTTPClient builds an http.Client for outbound web search requests. +// It uses utils.SSRFSafeDialContext, optional explicit or environment proxy, and +// redirect validation consistent with utils.NewSSRFSafeHTTPClient. +func NewSearchHTTPClient(timeout time.Duration, proxyURL string) (*http.Client, error) { + proxyURL = strings.TrimSpace(proxyURL) + def, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return nil, fmt.Errorf("default HTTP transport is not *http.Transport") + } + t := def.Clone() + t.DialContext = utils.SSRFSafeDialContext + + if proxyURL != "" { + if err := ValidateProxyURL(proxyURL); err != nil { + return nil, err + } + u, err := url.Parse(proxyURL) + if err != nil { + return nil, fmt.Errorf("invalid proxy_url: %w", err) + } + if u.Scheme == "" || u.Host == "" { + return nil, fmt.Errorf("invalid proxy_url: scheme and host are required") + } + t.Proxy = http.ProxyURL(u) + } else { + t.Proxy = http.ProxyFromEnvironment + } + + cfg := utils.DefaultSSRFSafeHTTPClientConfig() + return &http.Client{ + Timeout: timeout, + Transport: t, + CheckRedirect: ssrfSafeRedirect(cfg.MaxRedirects), + }, nil +} diff --git a/internal/infrastructure/web_search/proxy_test.go b/internal/infrastructure/web_search/proxy_test.go new file mode 100644 index 00000000..46f318d1 --- /dev/null +++ b/internal/infrastructure/web_search/proxy_test.go @@ -0,0 +1,78 @@ +package web_search + +import ( + "net/http" + "net/url" + "strings" + "testing" +) + +func TestValidateProxyURL(t *testing.T) { + tests := []struct { + name string + raw string + wantErr bool + }{ + {"empty", "", false}, + {"whitespace only", " ", false}, + {"no scheme private IP bare host:port", "192.168.0.1:3128", true}, + {"localhost http", "http://localhost:3128", true}, + {"direct IPv4 http", "http://192.168.1.1:3128", true}, + {"socks5 to IP blocked", "socks5://10.0.0.1:1080", true}, + {"bad scheme", "ftp://proxy.example:21", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateProxyURL(tt.raw) + if tt.wantErr && err == nil { + t.Fatalf("expected error, got nil") + } + if !tt.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestNewSearchHTTPClient_RejectsUnsafeProxy(t *testing.T) { + _, err := NewSearchHTTPClient(0, "http://127.0.0.1:3128") + if err == nil { + t.Fatal("expected error for disallowed proxy URL (127.0.0.1)") + } + if !strings.Contains(err.Error(), "SSRF") { + t.Fatalf("expected SSRF-related error, got: %v", err) + } +} + +func TestNewSearchHTTPClient_AcceptsEmptyProxy(t *testing.T) { + c, err := NewSearchHTTPClient(0, "") + if err != nil { + t.Fatal(err) + } + if c.Transport == nil { + t.Fatal("expected transport") + } + if c.CheckRedirect == nil { + t.Fatal("expected CheckRedirect for SSRF-safe redirects") + } +} + +func TestSsrfSafeRedirect_BlocksNonHTTPSScheme(t *testing.T) { + h := ssrfSafeRedirect(10) + req := &http.Request{URL: mustParse(t, "ftp://evil.com/")} + // len(via)==0 so first redirect + err := h(req, nil) + if err == nil { + t.Fatal("expected error for ftp redirect") + } +} + +func mustParse(t *testing.T, s string) *url.URL { + t.Helper() + u, err := url.Parse(s) + if err != nil { + t.Fatal(err) + } + return u +} diff --git a/internal/infrastructure/web_search/tavily.go b/internal/infrastructure/web_search/tavily.go index 614adfbf..4a1e3526 100644 --- a/internal/infrastructure/web_search/tavily.go +++ b/internal/infrastructure/web_search/tavily.go @@ -36,8 +36,9 @@ func NewTavilyProvider(params types.WebSearchProviderParameters) (interfaces.Web if params.APIKey == "" { return nil, fmt.Errorf("API key is required for Tavily provider") } - client := &http.Client{ - Timeout: defaultTavilyTimeout, + client, err := NewSearchHTTPClient(defaultTavilyTimeout, params.ProxyURL) + if err != nil { + return nil, err } return &TavilyProvider{ client: client, diff --git a/internal/types/web_search.go b/internal/types/web_search.go index 5b351d0d..1cf59210 100644 --- a/internal/types/web_search.go +++ b/internal/types/web_search.go @@ -22,6 +22,7 @@ type WebSearchConfig struct { EmbeddingDimension int `json:"embedding_dimension,omitempty"` // 嵌入维度(用于RAG压缩) RerankModelID string `json:"rerank_model_id,omitempty"` // 重排模型ID(用于RAG压缩) DocumentFragments int `json:"document_fragments,omitempty"` // 文档片段数量(用于RAG压缩) + ProxyURL string `json:"proxy_url,omitempty"` // Optional per-request proxy override; normally empty — use WebSearchProviderEntity.Parameters.proxy_url. Merged at call time when set. } // Value implements driver.Valuer interface for WebSearchConfig diff --git a/internal/types/web_search_provider.go b/internal/types/web_search_provider.go index 78a82761..58c14928 100644 --- a/internal/types/web_search_provider.go +++ b/internal/types/web_search_provider.go @@ -70,6 +70,9 @@ type WebSearchProviderParameters struct { APIKey string `yaml:"api_key" json:"api_key,omitempty"` // Google Custom Search Engine ID (only for Google provider) EngineID string `yaml:"engine_id" json:"engine_id,omitempty"` + // Optional HTTP/HTTPS proxy URL for outbound search requests (e.g. http://host:port); validated with utils.ValidateURLForSSRF. + // Does not replace the search API endpoint; only tunnels traffic to the official APIs. + ProxyURL string `yaml:"proxy_url" json:"proxy_url,omitempty"` // Provider-specific extra configuration for future extensibility ExtraConfig map[string]string `yaml:"extra_config" json:"extra_config,omitempty"` } @@ -117,6 +120,8 @@ type WebSearchProviderTypeInfo struct { RequiresAPIKey bool `json:"requires_api_key"` // Whether the provider requires an engine ID (e.g., Google CSE) RequiresEngineID bool `json:"requires_engine_id"` + // Whether optional proxy_url in parameters is honored for outbound requests + SupportsProxy bool `json:"supports_proxy"` // Description Description string `json:"description"` // URL to the provider's official website or documentation for obtaining credentials @@ -130,6 +135,7 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo { ID: "duckduckgo", Name: "DuckDuckGo", RequiresAPIKey: false, + SupportsProxy: true, Description: "DuckDuckGo Search (free, no API key required)", DocsURL: "https://duckduckgo.com/", }, @@ -137,6 +143,7 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo { ID: "bing", Name: "Bing", RequiresAPIKey: true, + SupportsProxy: true, Description: "Bing Search API (requires API key from Azure)", DocsURL: "https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/overview", }, @@ -145,6 +152,7 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo { Name: "Google", RequiresAPIKey: true, RequiresEngineID: true, + SupportsProxy: true, Description: "Google Custom Search API (requires API key and engine ID)", DocsURL: "https://developers.google.com/custom-search/v1/overview", }, @@ -152,6 +160,7 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo { ID: "tavily", Name: "Tavily", RequiresAPIKey: true, + SupportsProxy: true, Description: "Tavily Search API (requires API key)", DocsURL: "https://tavily.com/", }, From 927d3debff3d8c206425461191dca24294ad3a8b Mon Sep 17 00:00:00 2001 From: "ochan.kwon" Date: Thu, 16 Apr 2026 15:12:42 +0900 Subject: [PATCH 021/192] feat: pass IndexConfig to repositories with scalability options --- .../retriever/elasticsearch/v7/repository.go | 79 ++++- .../retriever/elasticsearch/v8/repository.go | 37 ++- .../repository/retriever/milvus/repository.go | 25 +- .../repository/retriever/milvus/structs.go | 2 + .../repository/retriever/qdrant/repository.go | 16 +- .../repository/retriever/qdrant/structs.go | 2 + .../retriever/weaviate/repository.go | 25 +- .../repository/retriever/weaviate/structs.go | 2 + internal/application/service/vectorstore.go | 20 +- .../application/service/vectorstore_test.go | 9 +- internal/container/container.go | 10 +- internal/container/engine_factory.go | 20 +- internal/types/vectorstore.go | 195 +++++++++++- internal/types/vectorstore_test.go | 300 +++++++++++++++++- 14 files changed, 673 insertions(+), 69 deletions(-) diff --git a/internal/application/repository/retriever/elasticsearch/v7/repository.go b/internal/application/repository/retriever/elasticsearch/v7/repository.go index 9feabb1d..75548346 100644 --- a/internal/application/repository/retriever/elasticsearch/v7/repository.go +++ b/internal/application/repository/retriever/elasticsearch/v7/repository.go @@ -12,7 +12,6 @@ import ( "encoding/json" "errors" "fmt" - "os" "strings" elasticsearchRetriever "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch" @@ -29,22 +28,31 @@ type elasticsearchRepository struct { client *elasticsearch.Client index string useKeywordSuffix bool // Whether to append .keyword suffix to ID field names in queries + numberOfShards int // Shard count for index creation (0 = ES default) + numberOfReplicas int // Replica count for index creation (-1 = unset, use ES default) } +// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v7 repository. +// indexCfg is optional — pass nil to use env var / default values (env path). func NewElasticsearchEngineRepository(client *elasticsearch.Client, config *config.Config, + indexCfg *typesLocal.IndexConfig, ) interfaces.RetrieveEngineRepository { log := logger.GetLogger(context.Background()) log.Info("[ElasticsearchV7] Initializing Elasticsearch v7 retriever engine repository") - indexName := os.Getenv("ELASTICSEARCH_INDEX") - if indexName == "" { - log.Warn("[ElasticsearchV7] ELASTICSEARCH_INDEX environment variable not set, using default index name") - indexName = "xwrag_default" - } + indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default") log.Infof("[ElasticsearchV7] Using index: %s", indexName) - res := &elasticsearchRepository{client: client, index: indexName} + res := &elasticsearchRepository{ + client: client, + index: indexName, + numberOfShards: indexCfg.GetNumberOfShards(0), + numberOfReplicas: indexCfg.GetNumberOfReplicas(-1), + } + if err := res.createIndexIfNotExists(context.Background()); err != nil { + log.Errorf("[ElasticsearchV7] Failed to create index: %v", err) + } res.detectFieldTypes(context.Background()) return res } @@ -118,6 +126,63 @@ func (e *elasticsearchRepository) detectFieldTypes(ctx context.Context) { } } +// createIndexIfNotExists checks if the specified index exists and creates it if not. +// Uses esapi low-level client since v7 SDK does not have typed API. +func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) error { + log := logger.GetLogger(ctx) + log.Debugf("[ElasticsearchV7] Checking if index exists: %s", e.index) + + res, err := e.client.Indices.Exists([]string{e.index}, e.client.Indices.Exists.WithContext(ctx)) + if err != nil { + return fmt.Errorf("check index existence: %w", err) + } + defer res.Body.Close() + + if !res.IsError() { + log.Debugf("[ElasticsearchV7] Index already exists: %s", e.index) + return nil + } + + // Build settings body with optional shards/replicas + var body string + if e.numberOfShards > 0 || e.numberOfReplicas >= 0 { + settings := make(map[string]interface{}) + if e.numberOfShards > 0 { + settings["number_of_shards"] = e.numberOfShards + } + if e.numberOfReplicas >= 0 { + settings["number_of_replicas"] = e.numberOfReplicas + } + bodyBytes, err := json.Marshal(map[string]interface{}{"settings": settings}) + if err != nil { + return fmt.Errorf("marshal index settings: %w", err) + } + body = string(bodyBytes) + } + + log.Infof("[ElasticsearchV7] Creating index: %s", e.index) + var opts []func(*esapi.IndicesCreateRequest) + opts = append(opts, e.client.Indices.Create.WithContext(ctx)) + if body != "" { + opts = append(opts, e.client.Indices.Create.WithBody(strings.NewReader(body))) + } + + createRes, err := e.client.Indices.Create(e.index, opts...) + if err != nil { + return fmt.Errorf("create index: %w", err) + } + defer createRes.Body.Close() + + if createRes.IsError() { + // Log detailed response server-side; return generic message to avoid leaking cluster info + log.Errorf("[ElasticsearchV7] Create index response: %s", createRes.String()) + return fmt.Errorf("failed to create index %s", e.index) + } + + log.Infof("[ElasticsearchV7] Index created successfully: %s", e.index) + return nil +} + func (e *elasticsearchRepository) EngineType() typesLocal.RetrieverEngineType { return typesLocal.ElasticsearchRetrieverEngineType } diff --git a/internal/application/repository/retriever/elasticsearch/v8/repository.go b/internal/application/repository/retriever/elasticsearch/v8/repository.go index ed25f084..9e9f989d 100644 --- a/internal/application/repository/retriever/elasticsearch/v8/repository.go +++ b/internal/application/repository/retriever/elasticsearch/v8/repository.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "os" "strings" elasticsearchRetriever "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch" @@ -24,25 +23,28 @@ type elasticsearchRepository struct { client *elasticsearch.TypedClient // Elasticsearch client instance index string // Name of the Elasticsearch index to use useKeywordSuffix bool // Whether to append .keyword suffix to ID field names in queries + numberOfShards int // Shard count for index creation (0 = ES default) + numberOfReplicas int // Replica count for index creation (-1 = unset, use ES default) } -// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v8 repository -// It sets up the index and returns a repository instance ready for use +// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v8 repository. +// indexCfg is optional — pass nil to use env var / default values (env path). func NewElasticsearchEngineRepository(client *elasticsearch.TypedClient, config *config.Config, + indexCfg *typesLocal.IndexConfig, ) interfaces.RetrieveEngineRepository { log := logger.GetLogger(context.Background()) log.Info("[Elasticsearch] Initializing Elasticsearch v8 retriever engine repository") - // Get index name from environment variable or use default - indexName := os.Getenv("ELASTICSEARCH_INDEX") - if indexName == "" { - log.Warn("[Elasticsearch] ELASTICSEARCH_INDEX environment variable not set, using default index name") - indexName = "xwrag_default" - } + indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default") // Create repository instance and ensure index exists - res := &elasticsearchRepository{client: client, index: indexName} + res := &elasticsearchRepository{ + client: client, + index: indexName, + numberOfShards: indexCfg.GetNumberOfShards(0), + numberOfReplicas: indexCfg.GetNumberOfReplicas(-1), + } if err := res.createIndexIfNotExists(context.Background()); err != nil { log.Errorf("[Elasticsearch] Failed to create index: %v", err) } else { @@ -355,9 +357,20 @@ func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) er return nil } - // Create index if it doesn't exist + // Create index if it doesn't exist, with optional shards/replicas settings log.Infof("[Elasticsearch] Creating index: %s", e.index) - _, err = e.client.Indices.Create(e.index).Do(ctx) + createReq := e.client.Indices.Create(e.index) + if e.numberOfShards > 0 || e.numberOfReplicas >= 0 { + settings := &types.IndexSettings{} + if e.numberOfShards > 0 { + settings.NumberOfShards = fmt.Sprintf("%d", e.numberOfShards) + } + if e.numberOfReplicas >= 0 { + settings.NumberOfReplicas = fmt.Sprintf("%d", e.numberOfReplicas) + } + createReq = createReq.Settings(settings) + } + _, err = createReq.Do(ctx) if err != nil { log.Errorf("[Elasticsearch] Failed to create index: %v", err) return err diff --git a/internal/application/repository/retriever/milvus/repository.go b/internal/application/repository/retriever/milvus/repository.go index 6e9344eb..7c99cf37 100644 --- a/internal/application/repository/retriever/milvus/repository.go +++ b/internal/application/repository/retriever/milvus/repository.go @@ -41,16 +41,13 @@ var ( fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID, fieldIsEnabled, fieldEmbedding} ) -// NewMilvusRetrieveEngineRepository creates and initializes a new Milvus repository -func NewMilvusRetrieveEngineRepository(client *client.Client) interfaces.RetrieveEngineRepository { +// NewMilvusRetrieveEngineRepository creates and initializes a new Milvus repository. +// indexCfg is optional — pass nil to use env var / default values (env path). +func NewMilvusRetrieveEngineRepository(client *client.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository { log := logger.GetLogger(context.Background()) log.Info("[Milvus] Initializing Milvus retriever engine repository") - collectionBaseName := os.Getenv(envMilvusCollection) - if collectionBaseName == "" { - log.Warn("[Milvus] MILVUS_COLLECTION environment variable not set, using default collection name") - collectionBaseName = defaultCollectionName - } + collectionBaseName := types.ResolveCollectionName(indexCfg, envMilvusCollection, defaultCollectionName) metricType := entity.IP if mt := os.Getenv(envMilvusMetricType); mt != "" { @@ -72,6 +69,8 @@ func NewMilvusRetrieveEngineRepository(client *client.Client) interfaces.Retriev client: client, collectionBaseName: collectionBaseName, metricType: metricType, + shardsNum: indexCfg.GetShardsNum(0), + replicaNumber: indexCfg.GetReplicaNumber(0), } log.Info("[Milvus] Successfully initialized repository") @@ -176,7 +175,11 @@ func (m *milvusRepository) ensureCollection(ctx context.Context, dimension int) } // Create collection - err = m.client.CreateCollection(ctx, client.NewCreateCollectionOption(collectionName, schema).WithIndexOptions(indexOpts...)) + createOpt := client.NewCreateCollectionOption(collectionName, schema).WithIndexOptions(indexOpts...) + if m.shardsNum > 0 { + createOpt = createOpt.WithShardNum(int32(m.shardsNum)) + } + err = m.client.CreateCollection(ctx, createOpt) if err != nil { log.Errorf("[Milvus] Failed to create collection: %v", err) return fmt.Errorf("failed to create collection: %w", err) @@ -185,7 +188,11 @@ func (m *milvusRepository) ensureCollection(ctx context.Context, dimension int) log.Infof("[Milvus] Successfully created collection %s", collectionName) } - loadTask, err := m.client.LoadCollection(ctx, client.NewLoadCollectionOption(collectionName)) + loadOpt := client.NewLoadCollectionOption(collectionName) + if m.replicaNumber > 0 { + loadOpt = loadOpt.WithReplica(m.replicaNumber) + } + loadTask, err := m.client.LoadCollection(ctx, loadOpt) if err != nil { log.Errorf("[Milvus] Failed to load collection: %v", err) return fmt.Errorf("failed to load collection: %w", err) diff --git a/internal/application/repository/retriever/milvus/structs.go b/internal/application/repository/retriever/milvus/structs.go index c3b44e0f..57375e65 100644 --- a/internal/application/repository/retriever/milvus/structs.go +++ b/internal/application/repository/retriever/milvus/structs.go @@ -12,6 +12,8 @@ type milvusRepository struct { client *client.Client collectionBaseName string metricType entity.MetricType + shardsNum int // 0 = use Milvus default (1) + replicaNumber int // 0 = use Milvus default (1); set at LoadCollection time // Cache for initialized collections (dimension -> true) initializedCollections sync.Map } diff --git a/internal/application/repository/retriever/qdrant/repository.go b/internal/application/repository/retriever/qdrant/repository.go index 29e74f5c..ee5f474b 100644 --- a/internal/application/repository/retriever/qdrant/repository.go +++ b/internal/application/repository/retriever/qdrant/repository.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "maps" - "os" "slices" "strings" "unicode/utf8" @@ -30,20 +29,19 @@ const ( fieldIsEnabled = "is_enabled" ) -// NewQdrantRetrieveEngineRepository creates and initializes a new Qdrant repository -func NewQdrantRetrieveEngineRepository(client *qdrant.Client) interfaces.RetrieveEngineRepository { +// NewQdrantRetrieveEngineRepository creates and initializes a new Qdrant repository. +// indexCfg is optional — pass nil to use env var / default values (env path). +func NewQdrantRetrieveEngineRepository(client *qdrant.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository { log := logger.GetLogger(context.Background()) log.Info("[Qdrant] Initializing Qdrant retriever engine repository") - collectionBaseName := os.Getenv(envQdrantCollection) - if collectionBaseName == "" { - log.Warn("[Qdrant] QDRANT_COLLECTION environment variable not set, using default collection name") - collectionBaseName = defaultCollectionName - } + collectionBaseName := types.ResolveCollectionName(indexCfg, envQdrantCollection, defaultCollectionName) res := &qdrantRepository{ client: client, collectionBaseName: collectionBaseName, + shardNumber: indexCfg.GetShardNumber(0), + replicationFactor: indexCfg.GetReplicationFactor(0), } log.Info("[Qdrant] Successfully initialized repository") @@ -82,6 +80,8 @@ func (q *qdrantRepository) ensureCollection(ctx context.Context, dimension int) Size: uint64(dimension), Distance: qdrant.Distance_Cosine, }), + ShardNumber: types.OptionalUint32(q.shardNumber), + ReplicationFactor: types.OptionalUint32(q.replicationFactor), }) if err != nil { log.Errorf("[Qdrant] Failed to create collection: %v", err) diff --git a/internal/application/repository/retriever/qdrant/structs.go b/internal/application/repository/retriever/qdrant/structs.go index 01a87ac7..89975b8c 100644 --- a/internal/application/repository/retriever/qdrant/structs.go +++ b/internal/application/repository/retriever/qdrant/structs.go @@ -9,6 +9,8 @@ import ( type qdrantRepository struct { client *qdrant.Client collectionBaseName string + shardNumber int // 0 = use Qdrant server default + replicationFactor int // 0 = use Qdrant server default // Cache for initialized collections (dimension -> true) initializedCollections sync.Map } diff --git a/internal/application/repository/retriever/weaviate/repository.go b/internal/application/repository/retriever/weaviate/repository.go index d8b477eb..7bdaec67 100644 --- a/internal/application/repository/retriever/weaviate/repository.go +++ b/internal/application/repository/retriever/weaviate/repository.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "maps" - "os" "slices" "strings" "unicode/utf8" @@ -35,19 +34,19 @@ const ( fieldID = "id" ) -func NewWeaviateRetrieveEngineRepository(client *weaviate.Client) interfaces.RetrieveEngineRepository { +// NewWeaviateRetrieveEngineRepository creates and initializes a new Weaviate repository. +// indexCfg is optional — pass nil to use env var / default values (env path). +func NewWeaviateRetrieveEngineRepository(client *weaviate.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository { log := logger.GetLogger(context.Background()) log.Info("[Weaviate] Initializing Weaviate retriever engine repository") - collectionBaseName := os.Getenv(envWeaviateCollection) - if collectionBaseName == "" { - log.Warn("[Weaviate] WEAVIATE_COLLECTION environment variable not set, using default collection name") - collectionBaseName = defaultCollectionName - } + collectionBaseName := types.ResolveCollectionName(indexCfg, envWeaviateCollection, defaultCollectionName) res := &weaviateRepository{ client: client, collectionBaseName: collectionBaseName, + replicationFactor: indexCfg.GetReplicationFactor(0), + desiredShardCount: indexCfg.GetDesiredShardCount(0), } log.Info("[Weaviate] Successfully initialized repository") @@ -137,6 +136,18 @@ func (w *weaviateRepository) ensureCollection(ctx context.Context, dimension int }, }, } + // Set replication factor if explicitly configured (> 0) + if w.replicationFactor > 0 { + classObj.ReplicationConfig = &models.ReplicationConfig{ + Factor: int64(w.replicationFactor), + } + } + // Set shard count if explicitly configured (> 0) + if w.desiredShardCount > 0 { + classObj.ShardingConfig = map[string]interface{}{ + "desiredCount": w.desiredShardCount, + } + } //创建collection if err = w.client.Schema().ClassCreator().WithClass(&classObj).Do(ctx); err != nil { log.Errorf("[Weaviate] Failed to create collection: %v", err) diff --git a/internal/application/repository/retriever/weaviate/structs.go b/internal/application/repository/retriever/weaviate/structs.go index ebc33638..32bf981c 100644 --- a/internal/application/repository/retriever/weaviate/structs.go +++ b/internal/application/repository/retriever/weaviate/structs.go @@ -9,6 +9,8 @@ import ( type weaviateRepository struct { client *weaviate.Client collectionBaseName string + replicationFactor int // 0 = use Weaviate server default + desiredShardCount int // 0 = use Weaviate server default // Cache for initialized collections (dimension -> true) initializedCollections sync.Map } diff --git a/internal/application/service/vectorstore.go b/internal/application/service/vectorstore.go index c677d248..77b91d05 100644 --- a/internal/application/service/vectorstore.go +++ b/internal/application/service/vectorstore.go @@ -2,6 +2,7 @@ package service import ( "context" + "fmt" "os" "time" @@ -44,6 +45,11 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto return err } + // 2.5. Index config validation (bounds, name characters) + if err := types.ValidateIndexConfig(store.IndexConfig); err != nil { + return err + } + // 3. Duplicate check — DB stores endpoint := store.ConnectionConfig.GetEndpoint() indexName := store.IndexConfig.GetIndexNameOrDefault(store.EngineType) @@ -66,7 +72,19 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto } } - // 5. Persist + // 5. Auto-detect server version via connection test. + // This is required for engines where the version determines the SDK (e.g., ES v7 vs v8). + // Without it, the wrong SDK may be used causing protocol errors (406, etc.). + version, err := s.TestConnection(ctx, store.EngineType, store.ConnectionConfig) + if err != nil { + return errors.NewBadRequestError( + fmt.Sprintf("connection test failed: %s. Ensure the server is reachable before saving.", err.Error())) + } + if version != "" { + store.ConnectionConfig.Version = version + } + + // 6. Persist logger.Infof(ctx, "Creating vector store: tenant=%d, name=%s, engine=%s", store.TenantID, secutils.SanitizeForLog(store.Name), store.EngineType) if err := s.repo.Create(ctx, store); err != nil { diff --git a/internal/application/service/vectorstore_test.go b/internal/application/service/vectorstore_test.go index 41fc47b9..8b6efb09 100644 --- a/internal/application/service/vectorstore_test.go +++ b/internal/application/service/vectorstore_test.go @@ -389,15 +389,14 @@ func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) { repo := &mockVectorStoreRepo{existsByEndpoint: false} svc := NewVectorStoreService(repo, nil, nil) + // Use postgres with UseDefaultConnection to avoid needing a real ES endpoint. + // The test verifies duplicate-check logic, not connectivity. store := &types.VectorStore{ TenantID: 1, Name: "new-store", - EngineType: types.ElasticsearchRetrieverEngineType, + EngineType: types.PostgresRetrieverEngineType, ConnectionConfig: types.ConnectionConfig{ - Addr: "http://es-new:9200", - }, - IndexConfig: types.IndexConfig{ - IndexName: "shared_index", + UseDefaultConnection: true, }, } diff --git a/internal/container/container.go b/internal/container/container.go index af91c69a..262d59b2 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -771,7 +771,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret if err != nil { log.Errorf("Create elasticsearch_v8 client failed: %v", err) } else { - elasticsearchRepo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg) + elasticsearchRepo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg, nil) if err := registry.Register( retriever.NewKVHybridRetrieveEngine( elasticsearchRepo, types.ElasticsearchRetrieverEngineType, @@ -793,7 +793,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret if err != nil { log.Errorf("Create elasticsearch_v7 client failed: %v", err) } else { - elasticsearchRepo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg) + elasticsearchRepo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg, nil) if err := registry.Register( retriever.NewKVHybridRetrieveEngine( elasticsearchRepo, types.ElasticsearchRetrieverEngineType, @@ -841,7 +841,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret if err != nil { log.Errorf("Create qdrant client failed: %v", err) } else { - qdrantRepository := qdrantRepo.NewQdrantRetrieveEngineRepository(client) + qdrantRepository := qdrantRepo.NewQdrantRetrieveEngineRepository(client, nil) if err := registry.Register( retriever.NewKVHybridRetrieveEngine( qdrantRepository, types.QdrantRetrieverEngineType, @@ -884,7 +884,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret if err != nil { log.Errorf("Create weaviate client failed: %v", err) } else { - weaviateRepository := weaviateRepo.NewWeaviateRetrieveEngineRepository(weaviateClient) + weaviateRepository := weaviateRepo.NewWeaviateRetrieveEngineRepository(weaviateClient, nil) if err := registry.Register( retriever.NewKVHybridRetrieveEngine( weaviateRepository, types.WeaviateRetrieverEngineType, @@ -921,7 +921,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret if err != nil { log.Errorf("Create milvus client failed: %v", err) } else { - milvusRepository := milvusRepo.NewMilvusRetrieveEngineRepository(milvusCli) + milvusRepository := milvusRepo.NewMilvusRetrieveEngineRepository(milvusCli, nil) if err := registry.Register( retriever.NewKVHybridRetrieveEngine( milvusRepository, types.MilvusRetrieverEngineType, diff --git a/internal/container/engine_factory.go b/internal/container/engine_factory.go index e9eb4939..0035baa5 100644 --- a/internal/container/engine_factory.go +++ b/internal/container/engine_factory.go @@ -84,9 +84,9 @@ func createElasticsearchEngine(store types.VectorStore, cfg *config.Config) (int // Version is auto-detected by PR2's TestConnection and saved to connection_config. // Empty version defaults to v8 (latest SDK). if isESv7(cc.Version) { - return createElasticsearchV7Engine(cc, cfg) + return createElasticsearchV7Engine(store, cfg) } - return createElasticsearchV8Engine(cc, cfg) + return createElasticsearchV8Engine(store, cfg) } // isESv7 checks if the detected ES version is 7.x. @@ -94,7 +94,8 @@ func isESv7(version string) bool { return strings.HasPrefix(version, "7.") } -func createElasticsearchV8Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) { +func createElasticsearchV8Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig client, err := elasticsearch.NewTypedClient(elasticsearch.Config{ Addresses: []string{cc.Addr}, Username: cc.Username, @@ -103,11 +104,12 @@ func createElasticsearchV8Engine(cc types.ConnectionConfig, cfg *config.Config) if err != nil { return nil, fmt.Errorf("create elasticsearch v8 client: %w", err) } - repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg) + repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig) return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil } -func createElasticsearchV7Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) { +func createElasticsearchV7Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) { + cc := store.ConnectionConfig client, err := esv7.NewClient(esv7.Config{ Addresses: []string{cc.Addr}, Username: cc.Username, @@ -116,7 +118,7 @@ func createElasticsearchV7Engine(cc types.ConnectionConfig, cfg *config.Config) if err != nil { return nil, fmt.Errorf("create elasticsearch v7 client: %w", err) } - repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg) + repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig) return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil } @@ -136,7 +138,7 @@ func createQdrantEngine(store types.VectorStore) (interfaces.RetrieveEngineServi if err != nil { return nil, fmt.Errorf("create qdrant client: %w", err) } - repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client) + repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client, &store.IndexConfig) return retriever.NewKVHybridRetrieveEngine(repo, types.QdrantRetrieverEngineType), nil } @@ -164,7 +166,7 @@ func createMilvusEngine(ctx context.Context, store types.VectorStore) (interface if err != nil { return nil, fmt.Errorf("create milvus client: %w", err) } - repo := milvusRepo.NewMilvusRetrieveEngineRepository(client) + repo := milvusRepo.NewMilvusRetrieveEngineRepository(client, &store.IndexConfig) return retriever.NewKVHybridRetrieveEngine(repo, types.MilvusRetrieverEngineType), nil } @@ -200,6 +202,6 @@ func createWeaviateEngine(store types.VectorStore) (interfaces.RetrieveEngineSer if err != nil { return nil, fmt.Errorf("create weaviate client: %w", err) } - repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client) + repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client, &store.IndexConfig) return retriever.NewKVHybridRetrieveEngine(repo, types.WeaviateRetrieverEngineType), nil } diff --git a/internal/types/vectorstore.go b/internal/types/vectorstore.go index e75eb771..e15b5045 100644 --- a/internal/types/vectorstore.go +++ b/internal/types/vectorstore.go @@ -4,6 +4,8 @@ import ( "database/sql/driver" "encoding/json" "fmt" + "os" + "regexp" "strings" "time" @@ -201,11 +203,19 @@ func (c ConnectionConfig) MaskSensitiveFields() ConnectionConfig { // IndexConfig holds optional index/collection configuration for the vector store. // If empty, engine-specific defaults are used. type IndexConfig struct { + // --- Existing fields --- IndexName string `yaml:"index_name" json:"index_name,omitempty"` // ES, OpenSearch NumberOfShards int `yaml:"number_of_shards" json:"number_of_shards,omitempty"` // ES, OpenSearch NumberOfReplicas int `yaml:"number_of_replicas" json:"number_of_replicas,omitempty"` // ES, OpenSearch - CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant + CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant, Weaviate CollectionName string `yaml:"collection_name" json:"collection_name,omitempty"` // Milvus + + // --- Scalability fields --- + ShardNumber int `yaml:"shard_number" json:"shard_number,omitempty"` // Qdrant: number of shards per collection + ReplicationFactor int `yaml:"replication_factor" json:"replication_factor,omitempty"` // Qdrant, Weaviate: number of replicas + ShardsNum int `yaml:"shards_num" json:"shards_num,omitempty"` // Milvus: number of shards per collection (CreateCollection) + ReplicaNumber int `yaml:"replica_number" json:"replica_number,omitempty"` // Milvus: in-memory replica count (LoadCollection) + DesiredShardCount int `yaml:"desired_shard_count" json:"desired_shard_count,omitempty"` // Weaviate: number of shards per collection } // Value implements the driver.Valuer interface. @@ -248,12 +258,181 @@ func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) strin if c.CollectionPrefix != "" { return c.CollectionPrefix } - return "WeKnora" + return "Weknora_embeddings" default: return c.IndexName } } +// --------------------------------------------------------------------------- +// IndexConfig — getter helpers (pointer receiver for nil safety) +// --------------------------------------------------------------------------- + +// GetNumberOfShards returns the configured number_of_shards, or def if unset/zero. +func (c *IndexConfig) GetNumberOfShards(def int) int { + if c != nil && c.NumberOfShards > 0 { + return c.NumberOfShards + } + return def +} + +// GetNumberOfReplicas returns the configured number_of_replicas, or def if unset/zero. +// Note: 0 replicas cannot be distinguished from "not set" because the int field with +// json:"omitempty" omits zero values. If zero-replica support is needed in the future, +// change the field type to *int. Currently 0 is treated as "use server default". +func (c *IndexConfig) GetNumberOfReplicas(def int) int { + if c != nil && c.NumberOfReplicas > 0 { + return c.NumberOfReplicas + } + return def +} + +// GetShardNumber returns the configured shard_number (Qdrant), or def if unset/zero. +func (c *IndexConfig) GetShardNumber(def int) int { + if c != nil && c.ShardNumber > 0 { + return c.ShardNumber + } + return def +} + +// GetReplicationFactor returns the configured replication_factor (Qdrant, Weaviate), or def if unset/zero. +func (c *IndexConfig) GetReplicationFactor(def int) int { + if c != nil && c.ReplicationFactor > 0 { + return c.ReplicationFactor + } + return def +} + +// GetShardsNum returns the configured shards_num (Milvus), or def if unset/zero. +func (c *IndexConfig) GetShardsNum(def int) int { + if c != nil && c.ShardsNum > 0 { + return c.ShardsNum + } + return def +} + +// GetReplicaNumber returns the configured replica_number (Milvus in-memory replicas), or def if unset/zero. +// Milvus replicas are set at LoadCollection time, not CreateCollection. +// They control how many query nodes hold the data in memory for read HA/throughput. +func (c *IndexConfig) GetReplicaNumber(def int) int { + if c != nil && c.ReplicaNumber > 0 { + return c.ReplicaNumber + } + return def +} + +// GetDesiredShardCount returns the configured desired_shard_count (Weaviate), or def if unset/zero. +func (c *IndexConfig) GetDesiredShardCount(def int) int { + if c != nil && c.DesiredShardCount > 0 { + return c.DesiredShardCount + } + return def +} + +// --------------------------------------------------------------------------- +// IndexConfig — resolve helpers (for Repository layer, with env var fallback) +// --------------------------------------------------------------------------- + +// ResolveIndexName returns the index name from IndexConfig, falling back to env var and then default. +// Used by Repository constructors. For service-layer duplicate checking, use GetIndexNameOrDefault instead. +func ResolveIndexName(ic *IndexConfig, envKey, defaultVal string) string { + if ic != nil && ic.IndexName != "" { + return ic.IndexName + } + if v := os.Getenv(envKey); v != "" { + return v + } + return defaultVal +} + +// ResolveCollectionName returns the collection name from IndexConfig, falling back to env var and then default. +// Priority: CollectionPrefix > CollectionName > env var > defaultVal. +// CollectionPrefix is checked first because Qdrant/Weaviate use it as the base name. +// CollectionName (Milvus) is checked second. If both are set, CollectionPrefix wins — +// this is safe because each VectorStore has a single engine type, so only one field is relevant. +func ResolveCollectionName(ic *IndexConfig, envKey, defaultVal string) string { + if ic != nil { + if ic.CollectionPrefix != "" { + return ic.CollectionPrefix + } + if ic.CollectionName != "" { + return ic.CollectionName + } + } + if v := os.Getenv(envKey); v != "" { + return v + } + return defaultVal +} + +// OptionalUint32 converts int to *uint32 for Qdrant SDK. +// Returns nil for values <= 0, which tells Qdrant to use its server default. +func OptionalUint32(v int) *uint32 { + if v <= 0 { + return nil + } + u := uint32(v) + return &u +} + +// --------------------------------------------------------------------------- +// IndexConfig — validation +// --------------------------------------------------------------------------- + +const ( + // maxShards is the upper bound for shard-related configuration values. + maxShards = 64 + // maxReplicas is the upper bound for replication-related configuration values. + maxReplicas = 10 +) + +// validIndexNamePattern restricts index/collection names to safe characters. +// Must start with a letter, followed by alphanumeric, underscore, or hyphen. Max 128 chars. +var validIndexNamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{0,127}$`) + +// ValidateIndexConfig checks IndexConfig fields for safe values. +// Call this from the service layer before persisting a VectorStore. +func ValidateIndexConfig(ic IndexConfig) error { + // Validate string fields (index/collection names) + if ic.IndexName != "" && !validIndexNamePattern.MatchString(ic.IndexName) { + return errors.NewValidationError( + "index_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)") + } + if ic.CollectionPrefix != "" && !validIndexNamePattern.MatchString(ic.CollectionPrefix) { + return errors.NewValidationError( + "collection_prefix must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)") + } + if ic.CollectionName != "" && !validIndexNamePattern.MatchString(ic.CollectionName) { + return errors.NewValidationError( + "collection_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)") + } + + // Validate numeric fields (shards/replicas) — must be within safe bounds + if ic.NumberOfShards < 0 || ic.NumberOfShards > maxShards { + return errors.NewValidationError(fmt.Sprintf("number_of_shards must be between 0 and %d", maxShards)) + } + if ic.NumberOfReplicas < 0 || ic.NumberOfReplicas > maxReplicas { + return errors.NewValidationError(fmt.Sprintf("number_of_replicas must be between 0 and %d", maxReplicas)) + } + if ic.ShardNumber < 0 || ic.ShardNumber > maxShards { + return errors.NewValidationError(fmt.Sprintf("shard_number must be between 0 and %d", maxShards)) + } + if ic.ReplicationFactor < 0 || ic.ReplicationFactor > maxReplicas { + return errors.NewValidationError(fmt.Sprintf("replication_factor must be between 0 and %d", maxReplicas)) + } + if ic.ShardsNum < 0 || ic.ShardsNum > maxShards { + return errors.NewValidationError(fmt.Sprintf("shards_num must be between 0 and %d", maxShards)) + } + if ic.ReplicaNumber < 0 || ic.ReplicaNumber > maxReplicas { + return errors.NewValidationError(fmt.Sprintf("replica_number must be between 0 and %d", maxReplicas)) + } + if ic.DesiredShardCount < 0 || ic.DesiredShardCount > maxShards { + return errors.NewValidationError(fmt.Sprintf("desired_shard_count must be between 0 and %d", maxShards)) + } + + return nil +} + // --------------------------------------------------------------------------- // VectorStoreResponse — API response DTO // --------------------------------------------------------------------------- @@ -339,7 +518,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo { {Name: "use_tls", Type: "boolean", Required: false, Default: false}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings"}, + {Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Prefix"}, + {Name: "shard_number", Type: "number", Required: false, Default: 1, Description: "Shard Number"}, + {Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"}, }, }, { @@ -351,7 +532,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo { {Name: "password", Type: "string", Required: false, Sensitive: true}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings"}, + {Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Name"}, + {Name: "shards_num", Type: "number", Required: false, Default: 1, Description: "Shards (write parallelism)"}, + {Name: "replica_number", Type: "number", Required: false, Default: 1, Description: "In-memory Replicas (read HA)"}, }, }, { @@ -364,7 +547,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo { {Name: "api_key", Type: "string", Required: false, Sensitive: true}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_prefix", Type: "string", Required: false, Default: "WeKnora"}, + {Name: "collection_prefix", Type: "string", Required: false, Default: "Weknora_embeddings", Description: "Collection Prefix"}, + {Name: "desired_shard_count", Type: "number", Required: false, Default: 1, Description: "Shard Count"}, + {Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"}, }, }, { diff --git a/internal/types/vectorstore_test.go b/internal/types/vectorstore_test.go index bf0d3bcf..e4481dd5 100644 --- a/internal/types/vectorstore_test.go +++ b/internal/types/vectorstore_test.go @@ -622,7 +622,7 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) { name: "weaviate default", config: IndexConfig{}, engineType: WeaviateRetrieverEngineType, - expected: "WeKnora", + expected: "Weknora_embeddings", }, // Postgres (no index config) { @@ -645,3 +645,301 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) { }) } } + +// --------------------------------------------------------------------------- +// IndexConfig — getter helpers +// --------------------------------------------------------------------------- + +func TestIndexConfig_GetterHelpers(t *testing.T) { + t.Run("nil receiver returns default", func(t *testing.T) { + var ic *IndexConfig + assert.Equal(t, 5, ic.GetNumberOfShards(5)) + assert.Equal(t, -1, ic.GetNumberOfReplicas(-1)) + assert.Equal(t, 0, ic.GetShardNumber(0)) + assert.Equal(t, 0, ic.GetReplicationFactor(0)) + assert.Equal(t, 1, ic.GetShardsNum(1)) + assert.Equal(t, 0, ic.GetReplicaNumber(0)) + assert.Equal(t, 0, ic.GetDesiredShardCount(0)) + }) + + t.Run("zero value returns default", func(t *testing.T) { + ic := &IndexConfig{} + assert.Equal(t, 5, ic.GetNumberOfShards(5)) + assert.Equal(t, -1, ic.GetNumberOfReplicas(-1)) + assert.Equal(t, 0, ic.GetShardNumber(0)) + assert.Equal(t, 0, ic.GetReplicationFactor(0)) + assert.Equal(t, 1, ic.GetShardsNum(1)) + assert.Equal(t, 0, ic.GetReplicaNumber(0)) + assert.Equal(t, 0, ic.GetDesiredShardCount(0)) + }) + + t.Run("positive value overrides default", func(t *testing.T) { + ic := &IndexConfig{ + NumberOfShards: 3, + NumberOfReplicas: 2, + ShardNumber: 4, + ReplicationFactor: 3, + ShardsNum: 5, + ReplicaNumber: 2, + DesiredShardCount: 3, + } + assert.Equal(t, 3, ic.GetNumberOfShards(1)) + assert.Equal(t, 2, ic.GetNumberOfReplicas(-1)) + assert.Equal(t, 4, ic.GetShardNumber(0)) + assert.Equal(t, 3, ic.GetReplicationFactor(0)) + assert.Equal(t, 5, ic.GetShardsNum(1)) + assert.Equal(t, 2, ic.GetReplicaNumber(0)) + assert.Equal(t, 3, ic.GetDesiredShardCount(0)) + }) + + t.Run("negative value returns default (treated as unset)", func(t *testing.T) { + ic := &IndexConfig{ + NumberOfShards: -1, + NumberOfReplicas: -1, + ShardNumber: -5, + ReplicationFactor: -1, + ShardsNum: -1, + ReplicaNumber: -1, + DesiredShardCount: -1, + } + assert.Equal(t, 1, ic.GetNumberOfShards(1)) + assert.Equal(t, -1, ic.GetNumberOfReplicas(-1)) + assert.Equal(t, 0, ic.GetShardNumber(0)) + assert.Equal(t, 0, ic.GetReplicationFactor(0)) + assert.Equal(t, 1, ic.GetShardsNum(1)) + assert.Equal(t, 0, ic.GetReplicaNumber(0)) + assert.Equal(t, 0, ic.GetDesiredShardCount(0)) + }) +} + +// --------------------------------------------------------------------------- +// IndexConfig — resolve helpers +// --------------------------------------------------------------------------- + +func TestResolveIndexName(t *testing.T) { + t.Run("nil IndexConfig falls back to env var", func(t *testing.T) { + t.Setenv("ELASTICSEARCH_INDEX", "env_index") + assert.Equal(t, "env_index", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "default")) + }) + + t.Run("nil IndexConfig falls back to default when env empty", func(t *testing.T) { + t.Setenv("ELASTICSEARCH_INDEX", "") + assert.Equal(t, "xwrag_default", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "xwrag_default")) + }) + + t.Run("IndexConfig value takes precedence over env var", func(t *testing.T) { + t.Setenv("ELASTICSEARCH_INDEX", "env_index") + ic := &IndexConfig{IndexName: "custom_index"} + assert.Equal(t, "custom_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default")) + }) + + t.Run("empty IndexConfig.IndexName falls back to env var", func(t *testing.T) { + t.Setenv("ELASTICSEARCH_INDEX", "env_index") + ic := &IndexConfig{} + assert.Equal(t, "env_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default")) + }) +} + +func TestResolveCollectionName(t *testing.T) { + t.Run("nil IndexConfig falls back to env var", func(t *testing.T) { + t.Setenv("QDRANT_COLLECTION", "env_collection") + assert.Equal(t, "env_collection", ResolveCollectionName(nil, "QDRANT_COLLECTION", "default")) + }) + + t.Run("CollectionPrefix takes precedence over CollectionName", func(t *testing.T) { + ic := &IndexConfig{CollectionPrefix: "prefix_name", CollectionName: "full_name"} + assert.Equal(t, "prefix_name", ResolveCollectionName(ic, "QDRANT_COLLECTION", "default")) + }) + + t.Run("CollectionName used when CollectionPrefix empty", func(t *testing.T) { + ic := &IndexConfig{CollectionName: "full_name"} + assert.Equal(t, "full_name", ResolveCollectionName(ic, "MILVUS_COLLECTION", "default")) + }) + + t.Run("empty IndexConfig falls back to default", func(t *testing.T) { + t.Setenv("QDRANT_COLLECTION", "") + ic := &IndexConfig{} + assert.Equal(t, "weknora_embeddings", ResolveCollectionName(ic, "QDRANT_COLLECTION", "weknora_embeddings")) + }) +} + +// --------------------------------------------------------------------------- +// OptionalUint32 +// --------------------------------------------------------------------------- + +func TestOptionalUint32(t *testing.T) { + t.Run("zero returns nil", func(t *testing.T) { + assert.Nil(t, OptionalUint32(0)) + }) + + t.Run("negative returns nil", func(t *testing.T) { + assert.Nil(t, OptionalUint32(-1)) + assert.Nil(t, OptionalUint32(-100)) + }) + + t.Run("positive returns pointer to uint32", func(t *testing.T) { + result := OptionalUint32(3) + require.NotNil(t, result) + assert.Equal(t, uint32(3), *result) + }) + + t.Run("large positive value", func(t *testing.T) { + result := OptionalUint32(64) + require.NotNil(t, result) + assert.Equal(t, uint32(64), *result) + }) +} + +// --------------------------------------------------------------------------- +// ValidateIndexConfig +// --------------------------------------------------------------------------- + +func TestValidateIndexConfig(t *testing.T) { + t.Run("empty config is valid", func(t *testing.T) { + assert.NoError(t, ValidateIndexConfig(IndexConfig{})) + }) + + t.Run("valid config with all fields", func(t *testing.T) { + ic := IndexConfig{ + IndexName: "my_index", + NumberOfShards: 3, + NumberOfReplicas: 1, + CollectionPrefix: "my_collection", + ShardNumber: 4, + ReplicationFactor: 2, + ShardsNum: 2, + ReplicaNumber: 3, + DesiredShardCount: 2, + } + assert.NoError(t, ValidateIndexConfig(ic)) + }) + + // --- Name validation --- + t.Run("index_name with special chars rejected", func(t *testing.T) { + ic := IndexConfig{IndexName: "my index*"} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "index_name") + }) + + t.Run("index_name starting with number rejected", func(t *testing.T) { + ic := IndexConfig{IndexName: "123abc"} + err := ValidateIndexConfig(ic) + require.Error(t, err) + }) + + t.Run("collection_prefix with slash rejected", func(t *testing.T) { + ic := IndexConfig{CollectionPrefix: "path/to/collection"} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "collection_prefix") + }) + + t.Run("collection_name with dot rejected", func(t *testing.T) { + ic := IndexConfig{CollectionName: "my.collection"} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "collection_name") + }) + + t.Run("valid names with underscore and hyphen", func(t *testing.T) { + ic := IndexConfig{ + IndexName: "my_index-v2", + CollectionPrefix: "Weknora_embeddings", + CollectionName: "custom-collection-name", + } + assert.NoError(t, ValidateIndexConfig(ic)) + }) + + // --- Numeric bounds --- + t.Run("number_of_shards exceeds max", func(t *testing.T) { + ic := IndexConfig{NumberOfShards: 100} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "number_of_shards") + }) + + t.Run("negative number_of_shards rejected", func(t *testing.T) { + ic := IndexConfig{NumberOfShards: -1} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "number_of_shards") + }) + + t.Run("replication_factor exceeds max", func(t *testing.T) { + ic := IndexConfig{ReplicationFactor: 50} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "replication_factor") + }) + + t.Run("shard_number at max boundary is valid", func(t *testing.T) { + ic := IndexConfig{ShardNumber: 64} + assert.NoError(t, ValidateIndexConfig(ic)) + }) + + t.Run("replication_factor at max boundary is valid", func(t *testing.T) { + ic := IndexConfig{ReplicationFactor: 10} + assert.NoError(t, ValidateIndexConfig(ic)) + }) + + t.Run("shards_num exceeds max", func(t *testing.T) { + ic := IndexConfig{ShardsNum: 999} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "shards_num") + }) + + t.Run("replica_number exceeds max", func(t *testing.T) { + ic := IndexConfig{ReplicaNumber: 50} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "replica_number") + }) + + t.Run("desired_shard_count exceeds max", func(t *testing.T) { + ic := IndexConfig{DesiredShardCount: 100} + err := ValidateIndexConfig(ic) + require.Error(t, err) + assert.Contains(t, err.Error(), "desired_shard_count") + }) +} + +// --------------------------------------------------------------------------- +// IndexConfig — scalability fields round-trip +// --------------------------------------------------------------------------- + +func TestIndexConfig_ScalabilityFieldsRoundTrip(t *testing.T) { + t.Run("scalability fields serialize and deserialize", func(t *testing.T) { + original := IndexConfig{ + IndexName: "my_index", + NumberOfShards: 3, + NumberOfReplicas: 1, + CollectionPrefix: "my_prefix", + ShardNumber: 4, + ReplicationFactor: 2, + ShardsNum: 5, + ReplicaNumber: 3, + DesiredShardCount: 2, + } + raw, err := original.Value() + require.NoError(t, err) + + var scanned IndexConfig + require.NoError(t, scanned.Scan(raw.([]byte))) + assert.Equal(t, original, scanned) + }) + + t.Run("scalability fields omitted when zero", func(t *testing.T) { + raw, err := IndexConfig{IndexName: "test"}.Value() + require.NoError(t, err) + + var parsed map[string]interface{} + require.NoError(t, json.Unmarshal(raw.([]byte), &parsed)) + assert.NotContains(t, parsed, "shard_number") + assert.NotContains(t, parsed, "replication_factor") + assert.NotContains(t, parsed, "shards_num") + assert.NotContains(t, parsed, "replica_number") + assert.NotContains(t, parsed, "desired_shard_count") + }) +} From 8fd1d613337772ffca4530940f5894f854948ef8 Mon Sep 17 00:00:00 2001 From: "ochan.kwon" Date: Thu, 16 Apr 2026 15:58:20 +0900 Subject: [PATCH 022/192] feat: add VectorStore management UI settings page --- frontend/src/api/vector-store.ts | 64 ++ frontend/src/i18n/locales/en-US.ts | 56 ++ frontend/src/i18n/locales/ko-KR.ts | 56 ++ frontend/src/i18n/locales/ru-RU.ts | 56 ++ frontend/src/i18n/locales/zh-CN.ts | 56 ++ frontend/src/views/settings/Settings.vue | 7 + .../views/settings/VectorStoreSettings.vue | 812 ++++++++++++++++++ internal/types/vectorstore.go | 94 +- internal/types/vectorstore_test.go | 19 +- scripts/dev.sh | 2 +- 10 files changed, 1155 insertions(+), 67 deletions(-) create mode 100644 frontend/src/api/vector-store.ts create mode 100644 frontend/src/views/settings/VectorStoreSettings.vue diff --git a/frontend/src/api/vector-store.ts b/frontend/src/api/vector-store.ts new file mode 100644 index 00000000..f9aeafe2 --- /dev/null +++ b/frontend/src/api/vector-store.ts @@ -0,0 +1,64 @@ +import { get, post, put, del } from '@/utils/request' + +// ===== Types ===== + +export interface VectorStoreEntity { + id?: string + name: string + engine_type: string + connection_config: Record + index_config: Record + source: 'env' | 'user' + readonly: boolean + tenant_id?: number + created_at?: string + updated_at?: string +} + +export interface VectorStoreTypeInfo { + type: string + display_name: string + connection_fields: FieldSchema[] + index_fields: FieldSchema[] +} + +export interface FieldSchema { + name: string + type: 'string' | 'number' | 'boolean' + required: boolean + sensitive?: boolean + description?: string + default?: any +} + +// ===== API Functions ===== + +export function listVectorStoreTypes(): Promise { + return get('/api/v1/vector-stores/types').then((res: any) => { + return res.success && res.data ? res.data : [] + }) +} + +export function listVectorStores(): Promise<{ success: boolean; data: VectorStoreEntity[] }> { + return get('/api/v1/vector-stores') +} + +export function createVectorStore(data: Partial) { + return post('/api/v1/vector-stores', data) +} + +export function updateVectorStore(id: string, data: Partial) { + return put(`/api/v1/vector-stores/${id}`, data) +} + +export function deleteVectorStore(id: string) { + return del(`/api/v1/vector-stores/${id}`) +} + +export function testVectorStoreRaw(data: { engine_type: string; connection_config: any }): Promise { + return post('/api/v1/vector-stores/test', data) +} + +export function testVectorStoreById(id: string): Promise { + return post(`/api/v1/vector-stores/${id}/test`, {}) +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 4bed7b8f..b6c1bcb9 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -573,6 +573,7 @@ export default { autoCheckUpdateDesc: 'When enabled, automatically check and download the latest version in the background.', memoryRequiresNeo4j: 'Memory feature requires Neo4j graph database. Please configure and enable Neo4j (set NEO4J_ENABLE=true) before enabling this feature.', memoryHowToEnable: 'View Neo4j Configuration Guide', + vectorStoreEngine: 'Vector DB Engine', parserEngine: 'Parser Engine', storageEngine: 'Storage Engine', mcpService: 'MCP Service', @@ -807,6 +808,61 @@ export default { testFailed: 'Connection test failed', } }, + vectorStoreSettings: { + title: 'Vector Database Engine', + description: 'Register and manage vector database instances for knowledge base search.', + storesTitle: 'Vector Databases', + addStore: 'Add Database', + editStore: 'Edit Database', + deleteConfirm: 'Are you sure you want to delete this vector database?', + emptyDesc: 'No vector databases configured. Click "Add Database" to get started.', + engineTypeLabel: 'Engine Type', + nameLabel: 'Name', + namePlaceholder: 'e.g., my-vector-store', + connectionInfo: 'Connection Info', + advancedIndexConfig: 'Advanced Settings', + fields: { + addr: 'URL', + host: 'Host', + port: 'Port', + username: 'Username', + password: 'Password', + api_key: 'API Key', + use_tls: 'Use TLS', + scheme: 'Scheme', + grpc_address: 'gRPC Address', + use_default_connection: 'Use Default Connection', + index_name: 'Index Name', + number_of_shards: 'Shards', + number_of_replicas: 'Replicas', + collection_prefix: 'Collection Prefix', + collection_name: 'Collection Name', + shard_number: 'Shard Number', + replication_factor: 'Replication Factor', + shards_num: 'Shards', + replica_number: 'In-memory Replicas', + desired_shard_count: 'Shard Count', + }, + envTag: 'DEFAULT', + testConnection: 'Test Connection', + testing: 'Testing...', + immutableNotice: 'Engine type, connection, and index settings cannot be changed after creation.\nTo change these, delete and recreate.', + validation: { + nameRequired: 'Name is required', + engineTypeRequired: 'Engine type is required', + fieldRequired: '{field} is required', + indexNamePattern: 'Must start with a letter. Only letters, numbers, underscore, and hyphen allowed (max 128)', + }, + toasts: { + storeCreated: 'Vector database created', + storeUpdated: 'Vector database updated', + storeDeleted: 'Vector database deleted', + testSuccess: 'Connection test succeeded', + testFailed: 'Connection test failed', + duplicateName: 'A vector database with this name already exists', + errorGeneric: 'An error occurred. Please try again.', + }, + }, chatHistorySettings: { title: 'Message Management', description: 'Configure chat history knowledge base to automatically index conversation messages for semantic search', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 7071150c..3d56ad79 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -435,6 +435,7 @@ export default { autoCheckUpdateDesc: '활성화하면 시작 시 최신 버전을 자동으로 확인하고 백그라운드에서 다운로드합니다.', memoryRequiresNeo4j: "기억 기능은 Neo4j 그래프 데이터베이스가 필요합니다. 이 기능을 활성화하기 전에 Neo4j를 구성하고 활성화해 주세요 (NEO4J_ENABLE=true 설정).", memoryHowToEnable: "Neo4j 구성 가이드 보기", + vectorStoreEngine: "벡터 DB 엔진", parserEngine: "파싱 엔진", storageEngine: "스토리지 엔진", mcpService: "MCP 서비스", @@ -666,6 +667,61 @@ export default { providerDeleted: "검색 엔진 프로바이더가 삭제되었습니다", }, }, + vectorStoreSettings: { + title: "벡터 데이터베이스 엔진", + description: "지식 베이스 검색을 위한 벡터 데이터베이스 인스턴스를 등록하고 관리합니다.", + storesTitle: "벡터 데이터베이스", + addStore: "데이터베이스 추가", + editStore: "데이터베이스 수정", + deleteConfirm: "이 벡터 데이터베이스를 삭제하시겠습니까?", + emptyDesc: "구성된 벡터 데이터베이스가 없습니다. '데이터베이스 추가'를 클릭하여 시작하세요.", + engineTypeLabel: "엔진 타입", + nameLabel: "이름", + namePlaceholder: "예: my-vector-store", + connectionInfo: "연결 정보", + advancedIndexConfig: "고급 설정", + fields: { + addr: "URL", + host: "호스트", + port: "포트", + username: "사용자명", + password: "비밀번호", + api_key: "API 키", + use_tls: "TLS 사용", + scheme: "프로토콜", + grpc_address: "gRPC 주소", + use_default_connection: "기본 연결 사용", + index_name: "인덱스 이름", + number_of_shards: "샤드 수", + number_of_replicas: "레플리카 수", + collection_prefix: "컬렉션 접두사", + collection_name: "컬렉션 이름", + shard_number: "샤드 수", + replication_factor: "레플리카 팩터", + shards_num: "샤드 수", + replica_number: "인메모리 레플리카", + desired_shard_count: "샤드 수", + }, + envTag: "DEFAULT", + testConnection: "연결 테스트", + testing: "테스트 중...", + immutableNotice: "엔진 타입, 연결 정보, 인덱스 설정은 생성 후 변경할 수 없습니다.\n변경이 필요하면 삭제 후 다시 생성하세요.", + validation: { + nameRequired: "이름은 필수입니다", + engineTypeRequired: "엔진 타입은 필수입니다", + fieldRequired: "{field}은(는) 필수입니다", + indexNamePattern: "영문자로 시작해야 합니다. 영문, 숫자, 밑줄, 하이픈만 허용 (최대 128자)", + }, + toasts: { + storeCreated: "벡터 데이터베이스가 생성되었습니다", + storeUpdated: "벡터 데이터베이스가 수정되었습니다", + storeDeleted: "벡터 데이터베이스가 삭제되었습니다", + testSuccess: "연결 테스트 성공", + testFailed: "연결 테스트 실패", + duplicateName: "동일한 이름의 벡터 데이터베이스가 이미 존재합니다", + errorGeneric: "오류가 발생했습니다. 다시 시도해 주세요.", + }, + }, chatHistorySettings: { title: "메시지 관리", description: "채팅 기록 지식베이스를 구성하여 대화 메시지를 자동으로 벡터화 인덱싱하여 시맨틱 검색을 지원합니다", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 022f76e9..dbe1cd54 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -552,6 +552,7 @@ export default { autoCheckUpdateDesc: 'При включении автоматически проверять и скачивать последнюю версию в фоновом режиме при запуске.', memoryRequiresNeo4j: 'Функция памяти требует графовую базу данных Neo4j. Пожалуйста, настройте и включите Neo4j (установите NEO4J_ENABLE=true) перед активацией этой функции.', memoryHowToEnable: 'Руководство по настройке Neo4j', + vectorStoreEngine: 'Движок векторной БД', parserEngine: 'Движок парсинга', storageEngine: 'Движок хранения', mcpService: 'Сервис MCP', @@ -785,6 +786,61 @@ export default { providerDeleted: 'Поисковый провайдер удалён', } }, + vectorStoreSettings: { + title: 'Движок векторной базы данных', + description: 'Регистрация и управление экземплярами векторных баз данных для поиска по базе знаний.', + storesTitle: 'Векторные базы данных', + addStore: 'Добавить базу данных', + editStore: 'Редактировать базу данных', + deleteConfirm: 'Вы уверены, что хотите удалить эту векторную базу данных?', + emptyDesc: 'Векторные базы данных не настроены. Нажмите "Добавить базу данных", чтобы начать.', + engineTypeLabel: 'Тип движка', + nameLabel: 'Название', + namePlaceholder: 'например, my-vector-store', + connectionInfo: 'Информация о подключении', + advancedIndexConfig: 'Расширенные настройки', + fields: { + addr: 'URL', + host: 'Хост', + port: 'Порт', + username: 'Имя пользователя', + password: 'Пароль', + api_key: 'API ключ', + use_tls: 'Использовать TLS', + scheme: 'Схема', + grpc_address: 'gRPC адрес', + use_default_connection: 'Использовать подключение по умолчанию', + index_name: 'Имя индекса', + number_of_shards: 'Шарды', + number_of_replicas: 'Реплики', + collection_prefix: 'Префикс коллекции', + collection_name: 'Имя коллекции', + shard_number: 'Количество шардов', + replication_factor: 'Фактор репликации', + shards_num: 'Шарды', + replica_number: 'Реплики в памяти', + desired_shard_count: 'Количество шардов', + }, + envTag: 'DEFAULT', + testConnection: 'Тест подключения', + testing: 'Тестирование...', + immutableNotice: 'Тип движка, подключение и настройки индекса нельзя изменить после создания.\nДля изменения удалите и создайте заново.', + validation: { + nameRequired: 'Название обязательно', + engineTypeRequired: 'Тип движка обязателен', + fieldRequired: '{field} обязательно', + indexNamePattern: 'Должно начинаться с буквы. Допускаются только буквы, цифры, подчёркивание и дефис (макс. 128)', + }, + toasts: { + storeCreated: 'Векторная база данных создана', + storeUpdated: 'Векторная база данных обновлена', + storeDeleted: 'Векторная база данных удалена', + testSuccess: 'Тест подключения успешен', + testFailed: 'Тест подключения не удался', + duplicateName: 'Векторная база данных с таким именем уже существует', + errorGeneric: 'Произошла ошибка. Попробуйте снова.', + }, + }, chatHistorySettings: { title: 'Управление сообщениями', description: 'Настройте базу знаний истории чата для автоматической индексации сообщений и семантического поиска', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 8a3180d1..34e7379f 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -432,6 +432,7 @@ export default { autoCheckUpdateDesc: '开启后自动检查并在后台下载最新版本安装包。', memoryRequiresNeo4j: "记忆功能依赖 Neo4j 图数据库,请先配置并启用 Neo4j(设置环境变量 NEO4J_ENABLE=true)后再开启此功能。", memoryHowToEnable: "查看 Neo4j 配置指南", + vectorStoreEngine: "向量数据库引擎", parserEngine: "解析引擎", storageEngine: "存储引擎", mcpService: "MCP服务", @@ -668,6 +669,61 @@ export default { testFailed: "连接测试失败", }, }, + vectorStoreSettings: { + title: "向量数据库引擎", + description: "注册和管理用于知识库搜索的向量数据库实例。", + storesTitle: "向量数据库", + addStore: "添加数据库", + editStore: "编辑数据库", + deleteConfirm: "确定要删除此向量数据库吗?", + emptyDesc: '尚未配置向量数据库。点击"添加数据库"开始设置。', + engineTypeLabel: "引擎类型", + nameLabel: "名称", + namePlaceholder: "例如:my-vector-store", + connectionInfo: "连接信息", + advancedIndexConfig: "高级设置", + fields: { + addr: "URL", + host: "主机", + port: "端口", + username: "用户名", + password: "密码", + api_key: "API 密钥", + use_tls: "使用 TLS", + scheme: "协议", + grpc_address: "gRPC 地址", + use_default_connection: "使用默认连接", + index_name: "索引名称", + number_of_shards: "分片数", + number_of_replicas: "副本数", + collection_prefix: "集合前缀", + collection_name: "集合名称", + shard_number: "分片数", + replication_factor: "副本因子", + shards_num: "分片数", + replica_number: "内存副本数", + desired_shard_count: "分片数", + }, + envTag: "DEFAULT", + testConnection: "测试连接", + testing: "测试中...", + immutableNotice: "创建后无法更改引擎类型、连接和索引设置。\n如需更改,请删除后重新创建。", + validation: { + nameRequired: "名称为必填项", + engineTypeRequired: "引擎类型为必填项", + fieldRequired: "{field}为必填项", + indexNamePattern: "必须以字母开头,仅允许字母、数字、下划线和连字符(最多128个字符)", + }, + toasts: { + storeCreated: "向量数据库已创建", + storeUpdated: "向量数据库已更新", + storeDeleted: "向量数据库已删除", + testSuccess: "连接测试成功", + testFailed: "连接测试失败", + duplicateName: "同名向量数据库已存在", + errorGeneric: "发生错误,请重试。", + }, + }, chatHistorySettings: { title: "消息管理", description: "配置聊天历史知识库,将对话消息自动向量化索引,实现语义搜索", diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue index 958f7c0a..d42d786d 100644 --- a/frontend/src/views/settings/Settings.vue +++ b/frontend/src/views/settings/Settings.vue @@ -117,6 +117,11 @@
+ +
+ +
+
@@ -169,6 +174,7 @@ import OllamaSettings from './OllamaSettings.vue' import McpSettings from './McpSettings.vue' import WebSearchSettings from './WebSearchSettings.vue' import ChatHistorySettings from './ChatHistorySettings.vue' +import VectorStoreSettings from './VectorStoreSettings.vue' import ParserEngineSettings from './ParserEngineSettings.vue' import StorageEngineSettings from './StorageEngineSettings.vue' import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue' @@ -189,6 +195,7 @@ const navItems = computed(() => [ { key: 'models', icon: 'control-platform', label: t('settings.modelManagement') }, { key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') }, { key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') }, + { key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') }, { key: 'parser', icon: 'file-search', label: t('settings.parserEngine') }, { key: 'storage', icon: 'cloud', label: t('settings.storageEngine') }, { key: 'mcp', icon: 'tools', label: t('settings.mcpService') }, diff --git a/frontend/src/views/settings/VectorStoreSettings.vue b/frontend/src/views/settings/VectorStoreSettings.vue new file mode 100644 index 00000000..3b8baae7 --- /dev/null +++ b/frontend/src/views/settings/VectorStoreSettings.vue @@ -0,0 +1,812 @@ + + + + + diff --git a/internal/types/vectorstore.go b/internal/types/vectorstore.go index e15b5045..f8f76bc6 100644 --- a/internal/types/vectorstore.go +++ b/internal/types/vectorstore.go @@ -484,79 +484,65 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo { return []VectorStoreTypeInfo{ { Type: "elasticsearch", - DisplayName: "Elasticsearch (Keywords + Vector)", + DisplayName: "Elasticsearch", ConnectionFields: []VectorStoreFieldInfo{ - {Name: "addr", Type: "string", Required: true, Description: "Elasticsearch URL (e.g., http://localhost:9200)"}, - {Name: "username", Type: "string", Required: false}, - {Name: "password", Type: "string", Required: false, Sensitive: true}, + {Name: "addr", Type: "string", Required: true, Description: "URL", Default: "http://localhost:9200"}, + {Name: "username", Type: "string", Required: false, Description: "Username", Default: "elastic"}, + {Name: "password", Type: "string", Required: false, Sensitive: true, Description: "Password"}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "index_name", Type: "string", Required: false, Default: "xwrag_default"}, - {Name: "number_of_shards", Type: "number", Required: false}, - {Name: "number_of_replicas", Type: "number", Required: false}, - }, - }, - { - Type: "postgres", - DisplayName: "PostgreSQL (Keywords + Vector)", - ConnectionFields: []VectorStoreFieldInfo{ - {Name: "use_default_connection", Type: "boolean", Required: false, Default: true, - Description: "Use the application's default database connection"}, - {Name: "addr", Type: "string", Required: false, - Description: "PostgreSQL connection string (required if use_default_connection is false)"}, - {Name: "username", Type: "string", Required: false}, - {Name: "password", Type: "string", Required: false, Sensitive: true}, + {Name: "index_name", Type: "string", Required: false, Description: "Index Name", Default: "weknora"}, + {Name: "number_of_shards", Type: "number", Required: false, Description: "Shards", Default: 4}, + {Name: "number_of_replicas", Type: "number", Required: false, Description: "Replicas", Default: 1}, }, }, + // PostgreSQL and SQLite are excluded from the type list because they only support + // the app's default DB connection (UseDefaultConnection=true). They appear as + // env stores when configured via RETRIEVE_DRIVER but cannot be added as DB stores. { Type: "qdrant", - DisplayName: "Qdrant (Keywords + Vector)", + DisplayName: "Qdrant", ConnectionFields: []VectorStoreFieldInfo{ - {Name: "host", Type: "string", Required: true, Description: "Qdrant host"}, - {Name: "port", Type: "number", Required: false, Default: 6334}, - {Name: "api_key", Type: "string", Required: false, Sensitive: true}, - {Name: "use_tls", Type: "boolean", Required: false, Default: false}, + {Name: "host", Type: "string", Required: true, Description: "Host", Default: "localhost"}, + {Name: "port", Type: "number", Required: false, Description: "Port", Default: 6334}, + {Name: "api_key", Type: "string", Required: false, Sensitive: true, Description: "API Key"}, + {Name: "use_tls", Type: "boolean", Required: false, Description: "Use TLS", Default: false}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Prefix"}, - {Name: "shard_number", Type: "number", Required: false, Default: 1, Description: "Shard Number"}, - {Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"}, + {Name: "collection_prefix", Type: "string", Required: false, Description: "Collection Prefix", Default: "weknora_embeddings"}, + {Name: "shard_number", Type: "number", Required: false, Description: "Shard Number", Default: 1}, + {Name: "replication_factor", Type: "number", Required: false, Description: "Replication Factor", Default: 1}, }, }, { Type: "milvus", - DisplayName: "Milvus (Keywords + Vector)", + DisplayName: "Milvus", ConnectionFields: []VectorStoreFieldInfo{ - {Name: "addr", Type: "string", Required: true, Description: "Milvus address (e.g., localhost:19530)"}, - {Name: "username", Type: "string", Required: false}, - {Name: "password", Type: "string", Required: false, Sensitive: true}, + {Name: "addr", Type: "string", Required: true, Description: "Address", Default: "localhost:19530"}, + {Name: "username", Type: "string", Required: false, Description: "Username", Default: "root"}, + {Name: "password", Type: "string", Required: false, Sensitive: true, Description: "Password"}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Name"}, - {Name: "shards_num", Type: "number", Required: false, Default: 1, Description: "Shards (write parallelism)"}, - {Name: "replica_number", Type: "number", Required: false, Default: 1, Description: "In-memory Replicas (read HA)"}, + {Name: "collection_name", Type: "string", Required: false, Description: "Collection Name", Default: "weknora_embeddings"}, + {Name: "shards_num", Type: "number", Required: false, Description: "Shards (write parallelism)", Default: 1}, + {Name: "replica_number", Type: "number", Required: false, Description: "In-memory Replicas (read HA)", Default: 1}, }, }, { Type: "weaviate", - DisplayName: "Weaviate (Keywords + Vector)", + DisplayName: "Weaviate", ConnectionFields: []VectorStoreFieldInfo{ - {Name: "host", Type: "string", Required: true, Description: "Weaviate host (e.g., weaviate:8080)"}, - {Name: "grpc_address", Type: "string", Required: false, Default: "weaviate:50051"}, - {Name: "scheme", Type: "string", Required: false, Default: "http"}, - {Name: "api_key", Type: "string", Required: false, Sensitive: true}, + {Name: "host", Type: "string", Required: true, Description: "Host", Default: "weaviate:8080"}, + {Name: "grpc_address", Type: "string", Required: false, Description: "gRPC Address", Default: "weaviate:50051"}, + {Name: "scheme", Type: "string", Required: false, Description: "Scheme", Default: "http"}, + {Name: "api_key", Type: "string", Required: false, Sensitive: true, Description: "API Key"}, }, IndexFields: []VectorStoreFieldInfo{ - {Name: "collection_prefix", Type: "string", Required: false, Default: "Weknora_embeddings", Description: "Collection Prefix"}, - {Name: "desired_shard_count", Type: "number", Required: false, Default: 1, Description: "Shard Count"}, - {Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"}, + {Name: "collection_prefix", Type: "string", Required: false, Description: "Collection Prefix", Default: "Weknora_embeddings"}, + {Name: "desired_shard_count", Type: "number", Required: false, Description: "Shard Count", Default: 1}, + {Name: "replication_factor", Type: "number", Required: false, Description: "Replication Factor", Default: 1}, }, }, - { - Type: "sqlite", - DisplayName: "SQLite (Keywords + Vector)", - ConnectionFields: []VectorStoreFieldInfo{}, - }, } } @@ -611,7 +597,7 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "postgres": return &VectorStore{ ID: "__env_postgres__", - Name: "postgres (env)", + Name: "PostgreSQL", EngineType: PostgresRetrieverEngineType, ConnectionConfig: ConnectionConfig{ UseDefaultConnection: true, @@ -620,13 +606,13 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "sqlite": return &VectorStore{ ID: "__env_sqlite__", - Name: "sqlite (env)", + Name: "SQLite", EngineType: SQLiteRetrieverEngineType, } case "elasticsearch_v8": return &VectorStore{ ID: "__env_elasticsearch_v8__", - Name: "elasticsearch v8 (env)", + Name: "Elasticsearch v8", EngineType: ElasticsearchRetrieverEngineType, ConnectionConfig: ConnectionConfig{ Addr: envLookup("ELASTICSEARCH_ADDR"), @@ -640,7 +626,7 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "elasticsearch_v7": return &VectorStore{ ID: "__env_elasticsearch_v7__", - Name: "elasticsearch v7 (env)", + Name: "Elasticsearch v7", EngineType: ElasticsearchRetrieverEngineType, ConnectionConfig: ConnectionConfig{ Addr: envLookup("ELASTICSEARCH_ADDR"), @@ -654,7 +640,7 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "qdrant": return &VectorStore{ ID: "__env_qdrant__", - Name: "qdrant (env)", + Name: "Qdrant", EngineType: QdrantRetrieverEngineType, ConnectionConfig: ConnectionConfig{ Host: envLookup("QDRANT_HOST"), @@ -664,7 +650,7 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "milvus": return &VectorStore{ ID: "__env_milvus__", - Name: "milvus (env)", + Name: "Milvus", EngineType: MilvusRetrieverEngineType, ConnectionConfig: ConnectionConfig{ Addr: envLookup("MILVUS_ADDRESS"), @@ -675,7 +661,7 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore case "weaviate": return &VectorStore{ ID: "__env_weaviate__", - Name: "weaviate (env)", + Name: "Weaviate", EngineType: WeaviateRetrieverEngineType, ConnectionConfig: ConnectionConfig{ Host: envLookup("WEAVIATE_HOST"), diff --git a/internal/types/vectorstore_test.go b/internal/types/vectorstore_test.go index e4481dd5..f957f037 100644 --- a/internal/types/vectorstore_test.go +++ b/internal/types/vectorstore_test.go @@ -63,7 +63,7 @@ func TestBuildEnvVectorStores(t *testing.T) { stores := BuildEnvVectorStores("postgres", lookup) require.Len(t, stores, 1) assert.Equal(t, "__env_postgres__", stores[0].ID) - assert.Equal(t, "postgres (env)", stores[0].Name) + assert.Equal(t, "PostgreSQL", stores[0].Name) assert.Equal(t, PostgresRetrieverEngineType, stores[0].EngineType) assert.True(t, stores[0].ConnectionConfig.UseDefaultConnection) }) @@ -198,8 +198,8 @@ func TestNewVectorStoreResponse(t *testing.T) { func TestGetVectorStoreTypes(t *testing.T) { types := GetVectorStoreTypes() - t.Run("returns 6 engine types", func(t *testing.T) { - assert.Len(t, types, 6) + t.Run("returns 4 engine types (excludes postgres and sqlite)", func(t *testing.T) { + assert.Len(t, types, 4) }) t.Run("type names match engine constants", func(t *testing.T) { @@ -208,11 +208,11 @@ func TestGetVectorStoreTypes(t *testing.T) { typeNames[i] = typ.Type } assert.Contains(t, typeNames, "elasticsearch") - assert.Contains(t, typeNames, "postgres") assert.Contains(t, typeNames, "qdrant") assert.Contains(t, typeNames, "milvus") assert.Contains(t, typeNames, "weaviate") - assert.Contains(t, typeNames, "sqlite") + assert.NotContains(t, typeNames, "postgres") + assert.NotContains(t, typeNames, "sqlite") }) t.Run("elasticsearch has connection and index fields", func(t *testing.T) { @@ -237,15 +237,10 @@ func TestGetVectorStoreTypes(t *testing.T) { assert.True(t, passwordField.Sensitive) }) - t.Run("sqlite has no connection fields", func(t *testing.T) { - var sqliteType VectorStoreTypeInfo + t.Run("display names have no parenthetical suffix", func(t *testing.T) { for _, typ := range types { - if typ.Type == "sqlite" { - sqliteType = typ - break - } + assert.NotContains(t, typ.DisplayName, "(", "display_name should not contain parenthetical suffix: %s", typ.DisplayName) } - assert.Empty(t, sqliteType.ConnectionFields) }) } diff --git a/scripts/dev.sh b/scripts/dev.sh index 79599a90..c4fcba5c 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -295,7 +295,7 @@ start_app() { log_warning "提示: 安装 Air 可以实现代码修改后自动重启" log_info "安装命令: go install github.com/air-verse/air@latest" LDFLAGS="$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'" - go run -ldflags="$LDFLAGS" cmd/server/main.go + go run -ldflags="$LDFLAGS" ./cmd/server/ fi } From e3b493e3166cb4a2819a37094153f5df76d7eecc Mon Sep 17 00:00:00 2001 From: Mao Meng <1707647656@qq.com> Date: Sun, 19 Apr 2026 00:02:31 +0800 Subject: [PATCH 023/192] fix: use constant-time comparison for API key validation --- internal/middleware/auth.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index e318b637..15c7fcec 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -2,6 +2,7 @@ package middleware import ( "context" + "crypto/subtle" "errors" "fmt" "log" @@ -178,7 +179,7 @@ func Auth( return } - if t == nil || t.APIKey != apiKey { + if t == nil || subtle.ConstantTimeCompare([]byte(t.APIKey), []byte(apiKey)) != 1 { c.JSON(http.StatusUnauthorized, gin.H{ "error": "Unauthorized: invalid API key", }) From 127654ee786806a0dbb8032c0c38c7eb3adfe82d Mon Sep 17 00:00:00 2001 From: "ochan.kwon" Date: Mon, 20 Apr 2026 11:18:51 +0900 Subject: [PATCH 024/192] feat: add vector_store_id column to knowledge_bases for per-KB vector store binding --- .../repository/knowledgebase_sqlite_test.go | 217 ++++++++++++++++++ internal/types/knowledgebase.go | 7 + internal/types/knowledgebase_test.go | 105 ++++++++- migrations/sqlite/000000_init.up.sql | 3 + .../000036_kb_vector_store_id.down.sql | 30 +++ .../000036_kb_vector_store_id.up.sql | 39 ++++ 6 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 internal/application/repository/knowledgebase_sqlite_test.go create mode 100644 migrations/versioned/000036_kb_vector_store_id.down.sql create mode 100644 migrations/versioned/000036_kb_vector_store_id.up.sql diff --git a/internal/application/repository/knowledgebase_sqlite_test.go b/internal/application/repository/knowledgebase_sqlite_test.go new file mode 100644 index 00000000..dc55c47f --- /dev/null +++ b/internal/application/repository/knowledgebase_sqlite_test.go @@ -0,0 +1,217 @@ +package repository + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +// knowledgeBasesTestDDL mirrors the `knowledge_bases` section of +// migrations/sqlite/000000_init.up.sql. We inline the DDL here instead of +// using GORM AutoMigrate because KnowledgeBase carries fields tagged with +// `type:jsonb`, which AutoMigrate does not map cleanly onto SQLite. +const knowledgeBasesTestDDL = ` +CREATE TABLE IF NOT EXISTS knowledge_bases ( + id VARCHAR(36) PRIMARY KEY, + name VARCHAR(255) NOT NULL, + description TEXT, + tenant_id INTEGER NOT NULL, + type VARCHAR(32) NOT NULL DEFAULT 'document', + chunking_config TEXT NOT NULL DEFAULT '{}', + image_processing_config TEXT NOT NULL DEFAULT '{}', + embedding_model_id VARCHAR(64) NOT NULL, + summary_model_id VARCHAR(64) NOT NULL, + cos_config TEXT NOT NULL DEFAULT '{}', + storage_provider_config TEXT DEFAULT NULL, + vlm_config TEXT NOT NULL DEFAULT '{}', + extract_config TEXT NULL DEFAULT NULL, + faq_config TEXT, + question_generation_config TEXT NULL, + is_temporary BOOLEAN NOT NULL DEFAULT 0, + is_pinned INTEGER NOT NULL DEFAULT 0, + pinned_at DATETIME NULL, + asr_config TEXT, + vector_store_id VARCHAR(36), + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + deleted_at DATETIME +); +` + +// setupKBTestDB creates an in-memory SQLite database containing the +// knowledge_bases table with the vector_store_id column included, so that +// tests can exercise the GORM behavior of the VectorStoreID field. +func setupKBTestDB(t *testing.T) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.Exec(knowledgeBasesTestDDL).Error) + return db +} + +// makeKB builds a minimal KnowledgeBase suitable for insert. Only the columns +// required by the schema above and any field we explicitly care about are set; +// the rest are left at their Go zero values and serialize to "{}" via their +// custom JSON valuers. +func makeKB(vectorStoreID *string) *types.KnowledgeBase { + return &types.KnowledgeBase{ + ID: uuid.New().String(), + Name: "test-kb", + TenantID: 1, + EmbeddingModelID: "test-embed", + SummaryModelID: "test-summary", + VectorStoreID: vectorStoreID, + } +} + +func kbStrPtr(s string) *string { return &s } + +// reloadKB fetches the KnowledgeBase back from the database using its ID. +func reloadKB(t *testing.T, db *gorm.DB, id string) types.KnowledgeBase { + t.Helper() + var got types.KnowledgeBase + require.NoError(t, db.First(&got, "id = ?", id).Error) + return got +} + +// TestKnowledgeBase_VectorStoreID_Save_Immutable verifies that db.Save(kb) +// — which WeKnora's UpdateKnowledgeBase repository path uses today — does +// NOT overwrite the vector_store_id column, thanks to the GORM +// `<-:create` tag. This is the primary automated defense for the H1 review +// finding (silent overwrite of the binding via full-struct UPDATE). +func TestKnowledgeBase_VectorStoreID_Save_Immutable(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(kbStrPtr("store-A")) + require.NoError(t, db.Create(original).Error) + + // Attempt to overwrite through the canonical Save() path. + mutated := *original + mutated.Name = "updated-name" + mutated.VectorStoreID = kbStrPtr("store-B") + require.NoError(t, db.Save(&mutated).Error) + + reloaded := reloadKB(t, db, original.ID) + + // Non-immutable fields must update. + assert.Equal(t, "updated-name", reloaded.Name, "Name must update through Save") + + // Immutable field must NOT update. + require.NotNil(t, reloaded.VectorStoreID, "VectorStoreID must remain set to the original value") + assert.Equal(t, "store-A", *reloaded.VectorStoreID, + "db.Save must not overwrite vector_store_id (enforced by GORM `<-:create` tag)") +} + +// TestKnowledgeBase_VectorStoreID_Updates_Immutable verifies that +// db.Updates(struct{...}) also honors `<-:create` and silently ignores the +// vector_store_id column. +func TestKnowledgeBase_VectorStoreID_Updates_Immutable(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(kbStrPtr("store-A")) + require.NoError(t, db.Create(original).Error) + + // Partial struct update that includes vector_store_id must not take effect. + err := db.Model(&types.KnowledgeBase{}). + Where("id = ?", original.ID). + Updates(types.KnowledgeBase{ + Name: "updated-name", + VectorStoreID: kbStrPtr("store-B"), + }).Error + require.NoError(t, err) + + reloaded := reloadKB(t, db, original.ID) + + assert.Equal(t, "updated-name", reloaded.Name) + require.NotNil(t, reloaded.VectorStoreID) + assert.Equal(t, "store-A", *reloaded.VectorStoreID, + "db.Updates must not overwrite vector_store_id (enforced by GORM `<-:create` tag)") +} + +// TestKnowledgeBase_VectorStoreID_Select_StillImmutable verifies that even +// an explicit Select("vector_store_id").Updates(...) does NOT bypass the +// `<-:create` tag. GORM's `<-:create` is strict: it withholds write +// permission from every UPDATE path, including selective updates. This is +// a stronger guarantee than a typical "column is protected unless you +// opt in" scheme. +// +// The implication for Phase 4 (cross-store migration) is that ORM-level +// updates cannot move bindings. Migration code must use raw SQL (db.Exec) +// — see TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch below. +func TestKnowledgeBase_VectorStoreID_Select_StillImmutable(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(kbStrPtr("store-A")) + require.NoError(t, db.Create(original).Error) + + err := db.Model(&types.KnowledgeBase{}). + Where("id = ?", original.ID). + Select("vector_store_id"). + Updates(map[string]interface{}{"vector_store_id": "store-B"}).Error + require.NoError(t, err) + + reloaded := reloadKB(t, db, original.ID) + require.NotNil(t, reloaded.VectorStoreID) + assert.Equal(t, "store-A", *reloaded.VectorStoreID, + "Select(\"vector_store_id\").Updates must NOT bypass <-:create; ORM is fully locked") +} + +// TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch documents that raw +// SQL UPDATE bypasses the GORM tag system entirely, as expected. Phase 4 +// cross-store migration is the only sanctioned caller of this path, and +// it must do so through a dedicated, narrowly-scoped repository method +// rather than through general Save/Updates/Select flows. +func TestKnowledgeBase_VectorStoreID_RawSQL_EscapeHatch(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(kbStrPtr("store-A")) + require.NoError(t, db.Create(original).Error) + + require.NoError(t, + db.Exec("UPDATE knowledge_bases SET vector_store_id = ? WHERE id = ?", + "store-B", original.ID).Error) + + reloaded := reloadKB(t, db, original.ID) + require.NotNil(t, reloaded.VectorStoreID) + assert.Equal(t, "store-B", *reloaded.VectorStoreID, + "raw SQL UPDATE bypasses GORM tags; Phase 4 migration must use this path through a dedicated method") +} + +// TestKnowledgeBase_VectorStoreID_Roundtrip_Nil verifies that a nil +// VectorStoreID is persisted as SQL NULL and loaded back as nil. +func TestKnowledgeBase_VectorStoreID_Roundtrip_Nil(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(nil) + require.NoError(t, db.Create(original).Error) + + reloaded := reloadKB(t, db, original.ID) + assert.Nil(t, reloaded.VectorStoreID, + "nil VectorStoreID must round-trip through the database as nil") + + // Extra assurance: column is actually NULL, not an empty string. + var nullCount int64 + require.NoError(t, + db.Table("knowledge_bases"). + Where("id = ? AND vector_store_id IS NULL", original.ID). + Count(&nullCount).Error) + assert.Equal(t, int64(1), nullCount, "nil must be stored as SQL NULL") +} + +// TestKnowledgeBase_VectorStoreID_Roundtrip_Value verifies that a non-nil +// VectorStoreID is persisted and loaded back with the same value. +func TestKnowledgeBase_VectorStoreID_Roundtrip_Value(t *testing.T) { + db := setupKBTestDB(t) + + original := makeKB(kbStrPtr("store-uuid-42")) + require.NoError(t, db.Create(original).Error) + + reloaded := reloadKB(t, db, original.ID) + require.NotNil(t, reloaded.VectorStoreID) + assert.Equal(t, "store-uuid-42", *reloaded.VectorStoreID) +} diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go index 462e5829..48100733 100644 --- a/internal/types/knowledgebase.go +++ b/internal/types/knowledgebase.go @@ -66,6 +66,13 @@ type KnowledgeBase struct { StorageProviderConfig *StorageProviderConfig `yaml:"storage_provider_config" json:"storage_provider_config" gorm:"column:storage_provider_config;type:jsonb"` // 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. + // When nil, the KB falls back to the tenant's effective engines derived from + // the RETRIEVE_DRIVER environment variable (env store flow). + // 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"` // Extract config ExtractConfig *ExtractConfig `yaml:"extract_config" json:"extract_config" gorm:"column:extract_config;type:json"` // FAQConfig stores FAQ specific configuration such as indexing strategy diff --git a/internal/types/knowledgebase_test.go b/internal/types/knowledgebase_test.go index 2f860b9f..a53cba2c 100644 --- a/internal/types/knowledgebase_test.go +++ b/internal/types/knowledgebase_test.go @@ -1,6 +1,10 @@ package types -import "testing" +import ( + "encoding/json" + "strings" + "testing" +) func TestParseProviderScheme(t *testing.T) { tests := []struct { @@ -53,3 +57,102 @@ func TestInferStorageFromFilePath(t *testing.T) { }) } } + +// strPtr returns a pointer to the given string, used to express *string literals in tests. +func strPtr(s string) *string { return &s } + +// TestKnowledgeBase_VectorStoreID_JSON covers (un)marshaling of the nullable +// VectorStoreID pointer, including the `omitempty` behavior and the three +// distinct JSON inputs (missing field, explicit null, explicit value). +// +// The `empty string pointer` case is fixed here as a behavior snapshot: PR1 +// accepts it and stores &"" verbatim because validation has not been added +// yet. A follow-up PR that introduces validation will convert this case into +// a rejection and flip the expectation in this test accordingly. +func TestKnowledgeBase_VectorStoreID_JSON(t *testing.T) { + t.Run("marshal nil omits field (omitempty)", func(t *testing.T) { + kb := KnowledgeBase{ID: "kb-1", VectorStoreID: nil} + b, err := json.Marshal(kb) + if err != nil { + t.Fatalf("json.Marshal returned error: %v", err) + } + if strings.Contains(string(b), `"vector_store_id"`) { + t.Errorf("expected vector_store_id to be omitted when nil, got: %s", b) + } + }) + + t.Run("marshal non-nil includes value", func(t *testing.T) { + kb := KnowledgeBase{ID: "kb-1", VectorStoreID: strPtr("store-uuid")} + b, err := json.Marshal(kb) + if err != nil { + t.Fatalf("json.Marshal returned error: %v", err) + } + if !strings.Contains(string(b), `"vector_store_id":"store-uuid"`) { + t.Errorf("expected vector_store_id to be serialized, got: %s", b) + } + }) + + unmarshalCases := []struct { + name string + body string + wantNil bool + wantValue string + }{ + {name: "missing field", body: `{"id":"kb-1"}`, wantNil: true}, + {name: "explicit null", body: `{"id":"kb-1","vector_store_id":null}`, wantNil: true}, + {name: "explicit value", body: `{"id":"kb-1","vector_store_id":"store-uuid"}`, wantValue: "store-uuid"}, + {name: "empty string pointer", body: `{"id":"kb-1","vector_store_id":""}`, wantValue: ""}, + } + for _, tt := range unmarshalCases { + t.Run(tt.name, func(t *testing.T) { + var kb KnowledgeBase + if err := json.Unmarshal([]byte(tt.body), &kb); err != nil { + t.Fatalf("json.Unmarshal returned error: %v", err) + } + if tt.wantNil { + if kb.VectorStoreID != nil { + t.Errorf("expected VectorStoreID to be nil, got &%q", *kb.VectorStoreID) + } + return + } + if kb.VectorStoreID == nil { + t.Fatalf("expected VectorStoreID to be &%q, got nil", tt.wantValue) + } + if *kb.VectorStoreID != tt.wantValue { + t.Errorf("expected VectorStoreID = %q, got %q", tt.wantValue, *kb.VectorStoreID) + } + }) + } +} + +// TestKnowledgeBase_UnmarshalJSON_WithVectorStoreID verifies that the custom +// UnmarshalJSON on KnowledgeBase (which shadows cos_config for legacy +// compatibility) still delegates the new vector_store_id field to the alias +// type path, without interfering with StorageProviderConfig inference. +func TestKnowledgeBase_UnmarshalJSON_WithVectorStoreID(t *testing.T) { + // Legacy cos_config + new vector_store_id in the same payload: both must map correctly. + body := `{ + "id": "kb-1", + "cos_config": {"provider": "cos", "bucket_name": "legacy-bucket"}, + "vector_store_id": "store-uuid" + }` + + var kb KnowledgeBase + if err := json.Unmarshal([]byte(body), &kb); err != nil { + t.Fatalf("json.Unmarshal returned error: %v", err) + } + + if kb.VectorStoreID == nil || *kb.VectorStoreID != "store-uuid" { + t.Errorf("expected VectorStoreID = &\"store-uuid\", got %v", kb.VectorStoreID) + } + if kb.StorageConfig.Provider != "cos" { + t.Errorf("expected legacy StorageConfig.Provider = cos, got %q", kb.StorageConfig.Provider) + } + if kb.StorageProviderConfig == nil || kb.StorageProviderConfig.Provider != "cos" { + t.Errorf("expected StorageProviderConfig.Provider auto-populated from cos_config, got %v", kb.StorageProviderConfig) + } + + // Regression guard: the aux struct inside UnmarshalJSON must not shadow vector_store_id. + // If a future change introduces such a shadow, the value above would fail to populate. +} + diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 4f7cb407..56499e0e 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -67,12 +67,15 @@ CREATE TABLE IF NOT EXISTS knowledge_bases ( is_pinned INTEGER NOT NULL DEFAULT 0, pinned_at DATETIME NULL, asr_config TEXT, + vector_store_id VARCHAR(36), created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, deleted_at DATETIME ); CREATE INDEX IF NOT EXISTS idx_knowledge_bases_tenant_id ON knowledge_bases(tenant_id); +CREATE INDEX IF NOT EXISTS idx_knowledge_bases_tenant_vector_store + ON knowledge_bases(tenant_id, vector_store_id); CREATE TABLE IF NOT EXISTS knowledges ( id VARCHAR(36) PRIMARY KEY, diff --git a/migrations/versioned/000036_kb_vector_store_id.down.sql b/migrations/versioned/000036_kb_vector_store_id.down.sql new file mode 100644 index 00000000..003b9ace --- /dev/null +++ b/migrations/versioned/000036_kb_vector_store_id.down.sql @@ -0,0 +1,30 @@ +-- Migration: 000036_kb_vector_store_id (rollback) +-- Description: Remove vector_store_id column and its index from knowledge_bases. +-- +-- WARNING: This rollback is destructive. It permanently drops the vector_store_id column +-- and all KB ↔ VectorStore bindings. To preserve bindings before rollback: +-- +-- CREATE TABLE knowledge_bases_vsid_backup AS +-- SELECT id, tenant_id, vector_store_id FROM knowledge_bases +-- WHERE vector_store_id IS NOT NULL; +-- +-- This down migration does NOT block execution when non-NULL rows exist, because blocking +-- during an emergency rollback can make an incident worse. The RAISE NOTICE below logs the +-- number of rows whose bindings will be lost so operators can reconstruct later if needed. +DO $$ +DECLARE non_null_count BIGINT; +BEGIN + SELECT COUNT(*) INTO non_null_count + FROM knowledge_bases WHERE vector_store_id IS NOT NULL; + IF non_null_count > 0 THEN + RAISE NOTICE '[Migration 000036 DOWN] Dropping vector_store_id with % non-NULL rows; these bindings will be lost', non_null_count; + ELSE + RAISE NOTICE '[Migration 000036 DOWN] Removing vector_store_id column from knowledge_bases'; + END IF; +END $$; + +DROP INDEX IF EXISTS idx_knowledge_bases_tenant_vector_store; + +ALTER TABLE knowledge_bases DROP COLUMN IF EXISTS vector_store_id; + +DO $$ BEGIN RAISE NOTICE '[Migration 000036 DOWN] vector_store_id column removed successfully'; END $$; diff --git a/migrations/versioned/000036_kb_vector_store_id.up.sql b/migrations/versioned/000036_kb_vector_store_id.up.sql new file mode 100644 index 00000000..2a3485f6 --- /dev/null +++ b/migrations/versioned/000036_kb_vector_store_id.up.sql @@ -0,0 +1,39 @@ +-- Migration: 000036_kb_vector_store_id +-- Description: Add vector_store_id column to knowledge_bases for per-KB VectorStore binding. +-- NULL means "use tenant's effective engines" (env store derived from RETRIEVE_DRIVER), +-- which preserves existing behavior for all pre-existing rows. +-- No foreign key: env store IDs are virtual (not present in vector_stores), and +-- VectorStore soft-delete must not cascade into KB references. Referential integrity is +-- enforced at the application layer. +-- On PostgreSQL 11+ this ALTER runs as metadata-only (O(1), no row rewrite) because the +-- column is nullable with no DEFAULT. PostgreSQL 10 and earlier are not supported. +DO $$ BEGIN RAISE NOTICE '[Migration 000036] Adding vector_store_id column to knowledge_bases'; END $$; + +ALTER TABLE knowledge_bases ADD COLUMN IF NOT EXISTS vector_store_id VARCHAR(36); + +COMMENT ON COLUMN knowledge_bases.vector_store_id IS + 'References vector_stores.id. NULL means tenant default (env store derived from RETRIEVE_DRIVER). ' + 'Immutable after creation (enforced at ORM and service layer). No FK by design.'; + +-- Composite index: tenant_id first to align with the dominant query pattern. All KB queries +-- start with `WHERE tenant_id = $1`, so the composite index enforces tenant-scoped plans and +-- hardens against accidental cross-tenant access. A full (non-partial) index is used because +-- the target end-state has most KBs bound to a store, making a partial index short-lived. +-- Storage cost is negligible at typical KB row counts. +CREATE INDEX IF NOT EXISTS idx_knowledge_bases_tenant_vector_store + ON knowledge_bases(tenant_id, vector_store_id); + +-- Note: CREATE INDEX here holds a SHARE lock briefly. For very large knowledge_bases tables +-- (hundreds of thousands of rows or more), operators may prefer CREATE INDEX CONCURRENTLY. +-- This requires running the statement outside a transaction, which the standard migration +-- runner does not support; execute the CONCURRENTLY variant from a separate operational +-- script in that case. Simply replacing the statement below with CONCURRENTLY inside this +-- file will cause the migration to fail and leave schema_migrations in a dirty state. + +DO $$ +DECLARE non_null_count BIGINT; +BEGIN + SELECT COUNT(*) INTO non_null_count + FROM knowledge_bases WHERE vector_store_id IS NOT NULL; + RAISE NOTICE '[Migration 000036] knowledge_bases.vector_store_id added (% non-NULL rows)', non_null_count; +END $$; From fff89d3abb38bc63aa43cc8a2e2d7c3f57341395 Mon Sep 17 00:00:00 2001 From: "bingxiang.cheng" Date: Fri, 17 Apr 2026 20:42:28 +0800 Subject: [PATCH 025/192] =?UTF-8?q?feat(openmaic-classroom):=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0OpenMAIC=E4=BA=92=E5=8A=A8=E8=AF=BE=E5=A0=82=E6=8A=80?= =?UTF-8?q?=E8=83=BD=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新建openmaic-classroom技能文档,描述技能功能和使用流程 - 实现基于RAG检索结果和PDF生成互动课件的核心能力 - 支持托管模式和本地部署两种API调用方式 - 设计生成请求构建流程及任务状态轮询机制 - 实现多文档合成课程集的处理方案及错误处理说明 - 提供完整API接口参考,包括健康检查、生成任务、PDF解析等 - 添加需求构建指南,指导如何将检索结果转为课程需求 - 新增rag-to-requirement.py脚本,实现RAG结果向需求结构化转换 - 规范请求参数和返回格式,兼容多语言和教学深度设定 - 明确MCP调用工具的识别与降级策略,提升接口调用体验 --- skills/openmaic-classroom/SKILL.md | 275 ++++++++++++++++ .../references/api-reference.md | 297 ++++++++++++++++++ .../references/requirement-builder.md | 135 ++++++++ .../scripts/rag-to-requirement.py | 194 ++++++++++++ 4 files changed, 901 insertions(+) create mode 100644 skills/openmaic-classroom/SKILL.md create mode 100644 skills/openmaic-classroom/references/api-reference.md create mode 100644 skills/openmaic-classroom/references/requirement-builder.md create mode 100644 skills/openmaic-classroom/scripts/rag-to-requirement.py diff --git a/skills/openmaic-classroom/SKILL.md b/skills/openmaic-classroom/SKILL.md new file mode 100644 index 00000000..c60a7b0e --- /dev/null +++ b/skills/openmaic-classroom/SKILL.md @@ -0,0 +1,275 @@ +--- +name: openmaic-classroom +description: 将 RAG 检索结果或文档块转换为 OpenMAIC 互动课程。当用户要求将知识库内容、检索到的文档片段、或上传的文档转换为教学课件/互动课堂时使用此技能。支持纯需求生成和基于 PDF 内容的课程生成。 +--- + +# OpenMAIC Classroom Generator + +将 WeKnora 知识库中的 RAG 检索结果或文档内容转换为 OpenMAIC 互动课程。 + +## 核心能力 + +1. **RAG → 课程**: 将知识检索结果提炼为教学需求(requirement),通过 OpenMAIC API 生成互动课程 +2. **PDF → 课程**: 解析用户上传的 PDF,结合内容生成课程 +3. **文档块 → 课程集**: 将多个文档块/知识片段组织为多阶段课程集 + +## 能力边界 + +> **通过 WeKnora 注册的 mcp-api-requester MCP 工具,你可以直接调用 OpenMAIC API**(HTTP POST/GET 请求)。 +> 该工具在 WeKnora agent 中注册为 `mcp_{service_name}_{tool_name}` 格式(如 `mcp_mcp_api_requester_make_request`)。 +> 不再需要向用户提供 curl 命令——直接在后台调用 API 并交付结果。 +> 如果 MCP 工具未配置或不可用,则降级为展示 curl 命令让用户手动执行。 + +> **⚠️ MCP 可用性检查(每次读取此文件后必须执行):** +> 在开始工作前,检查可用的 MCP 工具列表中是否存在名称包含 `mcp_api_requester` 的工具。 +> - **如果未找到**:必须提醒用户:"未检测到 `mcp_api_requester` MCP 服务。请先从 https://github.com/yryuu/mcp-api-requester 下载代码并部署,然后在 WeKnora 中注册该 MCP 服务。" +> - **如果已找到**:继续后续流程,使用该 MCP 工具调用 API。 + +## 模式选择 + +OpenMAIC 有两种使用模式,**根据用户场景选择**: + +| 模式 | Base URL | 认证方式 | 适用场景 | +|------|----------|----------|----------| +| 托管模式(推荐快速使用) | `https://open.maic.chat` | `Authorization: Bearer ` | 用户有 open.maic.chat 访问码,无需本地部署 | +| 本地模式 | `http://host.docker.internal:3000`(WeKnora 在容器内)或 `http://localhost:3000`(本地直接运行) | 无认证(本地自部署) | 用户自行部署了 OpenMAIC 实例 | + +**判断规则**: +- 用户提到"在线服务"、"open.maic.chat"、"访问码" → 使用托管模式 +- 用户提到"本地部署"、"自建" → 使用本地模式 +- 用户未明确说明时,优先询问用户使用哪个模式 + +## 前置条件 + +| 配置项 | 说明 | +|--------|------| +| 模式 | 托管模式 或 本地模式(见上方判断规则) | +| `accessCode` | 托管模式必需——访问码(以 `sk-` 开头),由用户在 open.maic.chat 获取 | +| 健康检查 | 调用前验证服务可用:`GET /api/health` | + +## 使用场景 + +当用户请求涉及以下内容时,使用此技能: +- "把这个文档做成课件" +- "基于检索结果生成课程" +- "为这个知识点创建互动课堂" +- "将知识库内容转换为教学材料" + +## 工作流程 + +### Phase 1: 确认输入源 + +确认课程生成的输入来源(三选一): + +1. **纯需求生成**: 用户直接描述教学主题,无需额外文档 + → 直接使用用户描述作为 `requirement`,**无需调用脚本** +2. **RAG 检索结果**: 先通过 `knowledge_search` 检索相关知识,再将结果组织为 requirement + → 使用 `scripts/rag-to-requirement.py` 脚本转换检索结果为结构化 requirement(见 Phase 1.1) +3. **PDF 文件**: 用户提供 PDF 文件路径,先解析再调用生成 API + → 提取 PDF 文本后构建 requirement,**无需调用脚本** + +### Phase 1.1: RAG 结果 → Requirement 转换(仅适用于场景 2) + +当场景 2 有 RAG 检索结果时,调用 `scripts/rag-to-requirement.py` 将 chunks 转换为 requirement: + +``` +execute_skill_script( + skill_name: "openmaic-classroom", + script_path: "scripts/rag-to-requirement.py", + input: '{"chunks": [...检索结果...], "query": "用户查询", "audience": "目标受众"}' +) +``` + +**input 参数格式(JSON 字符串,必须通过 `input` 参数传入,不可用 `--file`):** +- `chunks`(必填): RAG 检索结果数组,每项包含 `document_name`、`content`、`metadata` +- `query`(可选): 用户原始查询 +- `audience`(可选): 目标受众描述,默认"相关领域的学习者" +- `depth`(可选): 教学深度 `beginner|intermediate|advanced`,默认 `intermediate` +- `language`(可选): `zh-CN|en-US`,默认 `zh-CN` +- `focus_areas`(可选): 重点领域数组 + +**注意:** +- 必须将 chunks 数据作为 `input` 参数传入(等价于 `echo '{"chunks":...}' | python script.py`) +- **不要**在没有任何参数的情况下调用此脚本,否则会报错退出 +- 如果脚本执行失败,可直接根据检索结果手动构建 requirement + +### Phase 2: 构建 Generation Request + +根据输入源构建请求体,**字段说明**: + +| 字段 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `requirement` | string | 是 | 教学主题描述,1-2 句话 | +| `pdfContent` | object | 否 | PDF 解析后的文本和图片 | +| `language` | string | 否 | `"zh-CN"` 或 `"en-US"`,默认 `"zh-CN"` | +| `enableWebSearch` | bool | 否 | 是否启用网络搜索,默认 false | +| `enableImageGeneration` | bool | 否 | 是否生成配图,默认 false | +| `enableVideoGeneration` | bool | 否 | 是否生成视频,默认 false | +| `enableTTS` | bool | 否 | 是否生成语音朗读,默认 false | +| `agentMode` | string | 否 | `"default"` 或 `"generate"`,默认 `"default"` | + +场景适配: +- **场景 1(纯需求)**: `requirement` 直接使用用户描述 +- **场景 2(RAG 结果)**: `requirement` 使用 Phase 1.1 脚本输出中的 `requirement` 字段 +- **场景 3(PDF)**: `requirement` 根据 PDF 提取的文本构建,`pdfContent` 填入解析结果 + +### Phase 3: 调用 OpenMAIC API + +**优先方式**:通过 WeKnora 注册的 MCP 工具直接调用 API。 + +**第一步:识别 HTTP 请求工具** +- 在你可用的 MCP 工具中,找到用于 HTTP 请求的工具 +- 工具名称格式为 `mcp_{service_name}_{tool_name}`(如 `mcp_mcp_api_requester_make_request`) +- 通过工具描述(description)识别:寻找包含 "HTTP request"、"API"、"GET/POST" 等关键词的工具 +- 如果找不到 HTTP 请求类 MCP 工具,则降级为 curl 方案 + +**第二步:确定 Base URL 和认证 Header** + +| 模式 | Base URL | 认证 Header | +|------|----------|-------------| +| 托管模式 | `https://open.maic.chat` | `Authorization: Bearer ` | +| 本地模式 | `http://host.docker.internal:3000` 或 `http://localhost:3000` | 无 | + +**第三步:Feature Detection(发送可选功能前)** + +在发送生成请求前,先查询 `GET /api/health`(托管模式需带 auth header),检查返回的 `capabilities` 对象: + +```json +{ + "status": "ok", + "version": "...", + "capabilities": { + "webSearch": true, + "imageGeneration": false, + "videoGeneration": false, + "tts": true + } +} +``` + +- 只有当 `capabilities` 中某项为 `true` 时,才能在生成请求中将对应 feature flag 设为 `true` +- 如果服务器未返回 `capabilities`(旧版本),不要发送任何可选 feature flags + +**第四步:发送 POST 请求** + +使用识别到的 HTTP 请求工具发送请求。根据上面确定的模式和 URL 构造请求: + +**托管模式**: +```json +{ + "url": "https://open.maic.chat/api/generate-classroom", + "method": "POST", + "headers": { + "Content-Type": "application/json", + "Authorization": "Bearer " + }, + "body": { + "requirement": "..." + } +} +``` + +**本地模式**: +```json +{ + "url": "/api/generate-classroom", + "method": "POST", + "headers": { + "Content-Type": "application/json" + }, + "body": { + "requirement": "..." + } +} +``` + +**降级方式**:如果 MCP 工具不可用,向用户展示 curl 命令: + +**托管模式**: +```bash +curl -X POST https://open.maic.chat/api/generate-classroom \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer " \ + -d '{"requirement": "..."}' +``` + +**本地模式**: +```bash +curl -X POST /api/generate-classroom \ + -H "Content-Type: application/json" \ + -d '{"requirement": "..."}' +``` + +### Phase 4: 查询任务进度 + +API 返回 `jobId` 和 `pollUrl` 后,执行以下流程: + +**第 1 次查询(提交后立即执行)**: +1. 调用 HTTP 请求工具 `GET {pollUrl}` 获取当前状态 +2. 检查 `status`: + - 如果 `succeeded` → 进入 Phase 5 + - 如果 `failed` → 报告错误并停止 + - 如果 `queued` 或 `running` → **停止查询,告知用户**: + + > 课程正在生成中,预计需要 2-10 分钟。请稍后询问我查询进度。 + > Job ID: {jobId} + +**用户询问进度时(第 2 次查询)**: +1. 再次调用 `GET {pollUrl}` +2. 检查 `status`: + - 如果 `succeeded` → 进入 Phase 5 + - 如果 `failed` → 报告错误并停止 + - 如果仍在 `queued` 或 `running` → **停止查询,告知用户继续等待**: + + > 课程仍在生成中,请稍后再试。 + > Job ID: {jobId} + +**重要规则**: +- 提交后只查询 **1 次**,不要连续轮询 +- 用户询问进度时只查询 **1 次**,不要连续轮询 +- 仅在 `status` 为 `succeeded` 或 `failed` 时才继续下一步——否则必须停止并告知用户等待 +- 不要尝试重新提交 job——保持查询同一个 `pollUrl` + +### Phase 5: 返回结果 + +生成成功后,返回: + +``` +Classroom ID: +Classroom URL: +/classroom/ +``` + +托管模式的 URL 格式:`https://open.maic.chat/classroom/` + +> URL 必须以纯文本独占一行输出,不加粗、不加代码格式、不加 Markdown 链接。 + +## 错误处理 + +| 错误 | 含义 | 处理方式 | +|------|------|----------| +| 连接失败 | 网络不通或服务未启动 | 检查 Base URL 是否正确,服务是否启动 | +| 401 | 访问码无效(托管模式) | 告知用户到 open.maic.chat 检查或重新生成访问码 | +| 403 | 每日配额用尽(托管模式) | 告知每日 10 次限制,次日零点重置 | +| 500 | 服务器错误 | 建议稍后重试或切换到本地模式 | +| Provider 配置错误 | 模型/Provider/认证问题 | 引导用户检查 `.env.local` 或 `server-providers.yml` | + +## 多文档 → 课程集 + +当用户需要将多个文档/知识片段生成课程集时: + +1. 收集所有文档内容 +2. 为每个文档/主题分别生成 requirement +3. 通过 MCP 工具依次调用生成 API(不可并行,避免配额冲突) +4. 如果 MCP 工具不可用,依次提供对应的 curl 命令 +5. 汇总返回所有 Classroom URL + +## 注意事项 + +- 脚本在 Docker 沙箱中执行,**沙箱默认禁用网络访问** +- **通过 WeKnora MCP 工具,你可以直接调用 OpenMAIC API**——不再需要用户提供 curl 命令 +- MCP 工具名称格式为 `mcp_{service_name}_{tool_name}`,根据描述识别 HTTP 请求工具 +- 如果 MCP 工具未启用或不可用,降级为展示 curl 命令让用户手动执行 +- 单次生成任务预计 2-10 分钟,取决于内容复杂度和可选功能 +- 托管模式(open.maic.chat)每天最多 10 次生成配额,独立于 Web UI 配额 +- 如果用户在同一个 job 仍在运行时要求生成新课程,不要重复提交——先检查已有 job 状态 diff --git a/skills/openmaic-classroom/references/api-reference.md b/skills/openmaic-classroom/references/api-reference.md new file mode 100644 index 00000000..4693b267 --- /dev/null +++ b/skills/openmaic-classroom/references/api-reference.md @@ -0,0 +1,297 @@ +# OpenMAIC API Reference + +OpenMAIC 服务 API 接口规范。所有 API 基础路径为 `{base_url}/api`,默认 `http://localhost:3000/api`。 + +## 认证机制 + +- 如果 OpenMAIC 未设置 `ACCESS_CODE` 环境变量:所有接口开放 +- 如果设置了 `ACCESS_CODE`:需先通过 `/api/access-code/verify` 获取 cookie +- `/api/health` 始终无需认证 + +### 获取认证 Cookie + +``` +POST {base_url}/api/access-code/verify +Content-Type: application/json + +{ "code": "" } +``` + +成功返回 `{ "success": true, "valid": true }` 并设置 `openmaic_access` cookie(7 天有效)。 + +## 标准响应格式 + +**成功**: +```json +{ "success": true, ...additionalFields } +``` + +**错误**: +```json +{ "success": false, "errorCode": "", "error": "", "details?": "" } +``` + +--- + +## 核心端点 + +### 1. 健康检查 + +``` +GET {base_url}/api/health +``` + +响应: +```json +{ + "success": true, + "status": "ok", + "version": "0.1.0", + "capabilities": { + "webSearch": true, + "imageGeneration": false, + "videoGeneration": false, + "tts": true + } +} +``` + +> `capabilities` 用于功能检测,只在返回此字段时才启用对应的可选功能。 + +--- + +### 2. 生成课程(异步任务) + +#### 2a. 创建生成任务 + +``` +POST {base_url}/api/generate-classroom +Content-Type: application/json +``` + +请求体: +```json +{ + "requirement": "教学主题描述", + "pdfContent": { "text": "PDF文本内容", "images": [] }, + "enableWebSearch": false, + "enableImageGeneration": false, + "enableVideoGeneration": false, + "enableTTS": false, + "agentMode": "default" +} +``` + +成功响应 (202): +```json +{ + "success": true, + "jobId": "abc123xyz", + "status": "queued", + "step": "queued", + "message": "Classroom generation job queued", + "pollUrl": "{base_url}/api/generate-classroom/abc123xyz", + "pollIntervalMs": 5000 +} +``` + +错误: +- `400`: `requirement` 字段缺失 +- `500`: 内部错误 + +#### 2b. 轮询任务状态 + +``` +GET {pollUrl} +``` + +响应: +```json +{ + "success": true, + "jobId": "abc123xyz", + "status": "running", + "step": "generating_outlines", + "progress": 35, + "message": "Generating scene outlines...", + "pollUrl": "...", + "pollIntervalMs": 5000, + "scenesGenerated": 2, + "totalScenes": 6, + "result": null, + "error": null, + "done": false +} +``` + +最终成功响应: +```json +{ + "success": true, + "status": "succeeded", + "result": { + "classroomId": "Uyh82Y32ZK", + "url": "{base_url}/classroom/Uyh82Y32ZK", + "scenesCount": 6 + }, + "done": true +} +``` + +最终失败响应: +```json +{ + "success": true, + "status": "failed", + "error": "具体错误信息", + "done": true +} +``` + +--- + +### 3. 解析 PDF + +``` +POST {base_url}/api/parse-pdf +Content-Type: multipart/form-data +``` + +表单字段: +- `pdf`(文件,必填): PDF 文件 +- `providerId`(可选): PDF 提供商,默认 `"unpdf"` +- `apiKey`(可选): 提供商 API Key +- `baseUrl`(可选): 提供商基础 URL + +响应: +```json +{ + "success": true, + "data": { + "text": "提取的文本内容", + "images": [], + "metadata": { + "pageCount": 10, + "fileName": "document.pdf", + "fileSize": 1024000 + } + } +} +``` + +--- + +### 4. 课程存储 + +#### 4a. 获取课程 + +``` +GET {base_url}/api/classroom?id= +``` + +#### 4b. 持久化课程 + +``` +POST {base_url}/api/classroom +Content-Type: application/json + +{ "stage": {...}, "scenes": [...] } +``` + +--- + +### 5. Web 搜索 + +``` +POST {base_url}/api/web-search +Content-Type: application/json + +{ "query": "搜索关键词", "pdfText": "PDF上下文", "apiKey": "Tavily Key" } +``` + +--- + +### 6. 验证 LLM 连接 + +``` +POST {base_url}/api/verify-model +Content-Type: application/json + +{ "model": "openai:gpt-4o", "apiKey": "...", "baseUrl": "..." } +``` + +--- + +## 生成管线(逐步调用) + +如果需要更细粒度的控制,可以使用以下逐步生成端点代替 `/api/generate-classroom`: + +### A. 生成场景大纲(SSE 流) + +``` +POST {base_url}/api/generate/scene-outlines-stream +``` + +请求体: +```json +{ + "requirements": { "requirement": "主题", "userNickname": "用户昵称" }, + "pdfText": "PDF文本", + "pdfImages": [], + "researchContext": "网络搜索结果", + "agents": [] +} +``` + +Headers: +- `x-image-generation-enabled`: `"true"` 或 `"false"` +- `x-video-generation-enabled`: `"true"` 或 `"false"` + +SSE 事件类型:`languageDirective`、`outline`、`done`、`error`、`retry` + +### B. 生成场景内容 + +``` +POST {base_url}/api/generate/scene-content +Content-Type: application/json + +{ + "outline": {...}, + "allOutlines": [...], + "stageId": "stage-1", + "pdfImages": [], + "agents": [], + "languageDirective": "使用简体中文" +} +``` + +### C. 生成场景动作 + +``` +POST {base_url}/api/generate/scene-actions +Content-Type: application/json + +{ + "outline": {...}, + "allOutlines": [...], + "content": {...}, + "stageId": "stage-1", + "agents": [], + "languageDirective": "使用简体中文" +} +``` + +### D. 生成 Agent 画像 + +``` +POST {base_url}/api/generate/agent-profiles +Content-Type: application/json + +{ + "stageInfo": { "name": "入门阶段", "description": "..." }, + "sceneOutlines": [{ "title": "...", "description": "..." }], + "languageDirective": "使用简体中文", + "availableAvatars": [], + "avatarDescriptions": [] +} +``` diff --git a/skills/openmaic-classroom/references/requirement-builder.md b/skills/openmaic-classroom/references/requirement-builder.md new file mode 100644 index 00000000..c023e6d5 --- /dev/null +++ b/skills/openmaic-classroom/references/requirement-builder.md @@ -0,0 +1,135 @@ +# 需求构建指南 + +将 WeKnora RAG 检索结果转换为 OpenMAIC 课程生成所需的 `requirement` 格式。 + +## 核心原则 + +OpenMAIC 的 `requirement` 字段需要是**结构化的教学需求描述**,而不是原始文档片段。构建时需考虑: + +1. **教学主题**: 明确要教什么 +2. **目标受众**: 面向谁教学(如:初学者、专业人士、学生等) +3. **教学深度**: 入门级、中级、高级 +4. **内容范围**: 基于哪些知识源构建 + +## 转换模板 + +### 模板 1: 纯需求(无检索结果) + +用户直接描述需求时,直接使用用户描述作为 requirement: + +``` +用户: "帮我创建一个关于量子力学的入门课程" +→ requirement: "Create an introductory classroom on quantum mechanics for beginners" +``` + +### 模板 2: 基于 RAG 检索结果 + +``` +步骤: +1. 使用 knowledge_search 检索相关知识 +2. 从检索结果中提取: + - 核心主题/概念 + - 关键知识点 + - 文档来源信息 +3. 构建结构化 requirement +``` + +构建格式: +``` +基于以下知识内容,创建一个面向[目标受众]的[深度级别]课程: + +核心主题:[从检索结果提取的主要概念] +关键知识点: +- [知识点1] +- [知识点2] +- ... +内容来源:[文档名称列表] +``` + +### 模板 3: 基于单个文档 + +``` +基于文档《[文档名称]》的内容,创建一个面向[目标受众]的课程, +重点讲解以下方面: +- [用户指定的重点1] +- [用户指定的重点2] +``` + +### 模板 4: 基于多个文档/知识块 + +``` +综合以下文档内容,创建一个系统的课程: + +文档1《[名称1]》: [简要内容摘要] +文档2《[名称2]》: [简要内容摘要] +文档3《[名称3]》: [简要内容摘要] + +要求: +- 教学深度:[级别] +- 目标受众:[描述] +- 重点覆盖:[关键主题列表] +``` + +## 示例 + +### 示例 1: 技术文档 → 课程 + +``` +检索结果: +- 文档: "Kubernetes 部署指南.pdf" +- 关键内容: Pod 管理、Service 配置、Ingress 路由、存储卷 + +构建的 requirement: +"基于 Kubernetes 部署指南,创建一个面向 DevOps 工程师的中级课程。 +重点涵盖:Pod 生命周期管理、Service 和 Ingress 网络配置、持久化存储卷管理。 +课程应包含实践操作环节。" +``` + +### 示例 2: 产品手册 → 入门课程 + +``` +检索结果: +- 文档: "产品使用手册 v2.0.pdf" +- 关键内容: 产品概述、快速开始、核心功能、常见问题 + +构建的 requirement: +"基于产品使用手册 v2.0,为新用户创建一个入门课程。 +帮助用户快速了解产品核心功能,掌握基本操作方法, +并能够独立完成常见任务。课程语言为中文。" +``` + +### 示例 3: 研究论文 → 高级课程 + +``` +检索结果: +- 文档: "Transformer 架构研究综述.pdf" +- 关键内容: Attention 机制、位置编码、多头注意力、训练技巧 + +构建的 requirement: +"基于 Transformer 架构研究综述,为具有深度学习基础的研究人员 +创建高级课程。深入讲解 Attention 机制的数学原理、位置编码的 +各种变体、多头注意力的设计动机,以及训练大模型时的实践技巧。" +``` + +## 可选功能配置建议 + +在构建 request 时,根据用户需求推荐可选功能: + +| 场景 | 推荐功能 | +|------|----------| +| 技术培训 | `enableWebSearch: true`(补充最新技术动态) | +| 产品介绍 | `enableImageGeneration: true`(生成产品截图/界面图) | +| 市场营销 | `enableImageGeneration: true, enableVideoGeneration: true` | +| 语言教学 | `enableTTS: true`(语音朗读) | +| 学术研究 | 默认配置即可(不需要多媒体) | + +## 多文档处理 + +当需要将多个独立文档分别生成课程时: + +1. 为每个文档单独构建 requirement +2. 依次调用生成 API(不可并行) +3. 每完成一个即返回 URL,继续下一个 +4. 最终汇总所有 Classroom URL + +> 注意:OpenMAIC 托管模式每天最多 10 次生成配额,本地模式取决于 LLM Provider 配额。 diff --git a/skills/openmaic-classroom/scripts/rag-to-requirement.py b/skills/openmaic-classroom/scripts/rag-to-requirement.py new file mode 100644 index 00000000..f37290a7 --- /dev/null +++ b/skills/openmaic-classroom/scripts/rag-to-requirement.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +""" +RAG 检索结果 → OpenMAIC Requirement 转换器 + +将 WeKnora RAG 检索结果转换为结构化的 OpenMAIC 课程生成需求描述。 +此脚本仅做数据转换,不涉及网络调用。 + +用法: + echo '{"chunks": [...], "audience": "初学者"}' | python scripts/rag-to-requirement.py + python scripts/rag-to-requirement.py --file results.json + +输入格式 (JSON): +{ + "chunks": [ + { + "document_name": "文档A.pdf", + "content": "文档内容片段...", + "metadata": {"page": 5, "section": "第三章"} + } + ], + "query": "用户原始查询(可选)", + "audience": "目标受众描述(可选,默认'相关领域的学习者')", + "depth": "教学深度: beginner|intermediate|advanced(可选,默认'intermediate')", + "language": "zh-CN|en-US(可选,默认'zh-CN')", + "focus_areas": ["重点领域1", "重点领域2"] # 可选 +} + +输出格式 (JSON): +{ + "requirement": "结构化的教学需求描述", + "metadata": { + "source_documents": ["文档A.pdf", "文档B.pdf"], + "total_chunks": 5, + "audience": "初学者", + "depth": "intermediate", + "language": "zh-CN" + } +} +""" + +import json +import sys +from typing import Any + + +def extract_key_topics(chunks: list[dict], max_topics: int = 5) -> list[str]: + """从文档块中提取关键主题(基于内容摘要和 section 信息)。""" + topics = [] + seen = set() + + for chunk in chunks: + metadata = chunk.get("metadata", {}) + # 优先使用 section/chapter 信息 + for key in ("section", "chapter", "heading", "title"): + if key in metadata and metadata[key] not in seen: + topics.append(metadata[key]) + seen.add(metadata[key]) + if len(topics) >= max_topics: + return topics + + # 如果 section 信息不足,从内容前 50 字提取 + for chunk in chunks: + content = chunk.get("content", "")[:50].strip() + if content and content not in seen: + topics.append(content + "...") + seen.add(content) + if len(topics) >= max_topics: + break + + return topics + + +def build_requirement(data: dict[str, Any]) -> str: + """将 RAG 结果构建为 OpenMAIC requirement 字符串。""" + chunks = data.get("chunks", []) + query = data.get("query", "") + audience = data.get("audience", "相关领域的学习者") + depth = data.get("depth", "intermediate") + language = data.get("language", "zh-CN") + focus_areas = data.get("focus_areas", []) + + depth_map = { + "beginner": "入门", + "intermediate": "中级", + "advanced": "高级", + } + depth_cn = depth_map.get(depth, "中级") + + # 提取文档名称 + source_docs = list({c.get("document_name", "未知文档") for c in chunks}) + + # 提取关键主题 + key_topics = extract_key_topics(chunks) + + # 构建 requirement + parts = [] + + # 开头:基于什么内容,为谁创建什么课程 + if query: + parts.append(f"基于以下知识库内容,为{audience}创建一个{depth_cn}课程。") + parts.append(f"用户原始需求:{query}") + else: + parts.append(f"基于以下知识库内容,为{audience}创建一个{depth_cn}课程。") + + # 内容来源 + if source_docs: + docs_str = "、".join(source_docs[:5]) + if len(source_docs) > 5: + docs_str += f" 等{len(source_docs)}个文档" + parts.append(f"\n内容来源:{docs_str}") + + # 关键主题 + if key_topics: + parts.append("\n核心主题:") + for i, topic in enumerate(key_topics, 1): + parts.append(f" {i}. {topic}") + + # 重点领域 + if focus_areas: + parts.append("\n重点覆盖:") + for area in focus_areas: + parts.append(f" - {area}") + + # 语言要求 + if language == "zh-CN": + parts.append("\n请使用中文生成课程内容。") + + return "\n".join(parts) + + +def process(input_data: dict[str, Any]) -> dict[str, Any]: + """主处理函数。""" + chunks = input_data.get("chunks", []) + if not chunks: + return { + "requirement": input_data.get("query", ""), + "metadata": { + "source_documents": [], + "total_chunks": 0, + "error": "未提供检索结果,使用原始查询作为 requirement", + }, + } + + requirement = build_requirement(input_data) + + source_docs = list({c.get("document_name", "未知文档") for c in chunks}) + + return { + "requirement": requirement, + "metadata": { + "source_documents": source_docs, + "total_chunks": len(chunks), + "audience": input_data.get("audience", "相关领域的学习者"), + "depth": input_data.get("depth", "intermediate"), + "language": input_data.get("language", "zh-CN"), + }, + } + + +def main() -> None: + """入口:从 stdin 或文件读取输入,输出 JSON 结果。""" + import argparse + + parser = argparse.ArgumentParser(description="RAG 结果 → OpenMAIC Requirement 转换器") + parser.add_argument("--file", "-f", help="输入 JSON 文件路径") + args = parser.parse_args() + + # 读取输入 + if args.file: + with open(args.file, "r", encoding="utf-8") as f: + input_data = json.load(f) + else: + input_text = sys.stdin.read() + if not input_text.strip(): + print( + "错误: 未提供输入数据。用法:\n" + " echo '{\"chunks\": [...]}' | python rag-to-requirement.py\n" + " python rag-to-requirement.py --file input.json", + file=sys.stderr, + ) + sys.exit(1) + try: + input_data = json.loads(input_text) + except json.JSONDecodeError as e: + print(f"错误: 输入 JSON 解析失败: {e}", file=sys.stderr) + sys.exit(1) + + # 处理并输出 + result = process(input_data) + print(json.dumps(result, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() From 8f671817a3399221f6f89eb913a2705b0c769c96 Mon Sep 17 00:00:00 2001 From: "bingxiang.cheng" Date: Fri, 17 Apr 2026 22:11:24 +0800 Subject: [PATCH 026/192] =?UTF-8?q?refactor(openmaic-classroom):=20?= =?UTF-8?q?=E8=A7=84=E8=8C=83=E6=96=87=E6=A1=A3=E5=B9=B6=E5=BC=BA=E5=8C=96?= =?UTF-8?q?mcp-api-requester=E8=B0=83=E7=94=A8=E8=A6=81=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 重新排版和规范技能说明文档,提升可读性 - 明确强调必须使用WeKnora的mcp-api-requester MCP工具调用OpenMAIC API - 取消curl命令降级方案,改为引导用户部署mcp-api-requester服务 - 增强本地模式Base URL处理,替换localhost和127.0.0.1为host.docker.internal - 完善错误处理和任务状态查询流程说明 - 更新API参考文档,统一接口描述和响应格式 - 细化多文档生成课程集的调用和错误引导逻辑 - 提示单次生成任务时间及托管模式配额限制 --- .../openmaic-classroom/SKILL.md | 43 +++++++++---------- .../references/api-reference.md | 0 .../references/requirement-builder.md | 0 .../scripts/rag-to-requirement.py | 0 4 files changed, 20 insertions(+), 23 deletions(-) rename skills/{ => preloaded}/openmaic-classroom/SKILL.md (85%) rename skills/{ => preloaded}/openmaic-classroom/references/api-reference.md (100%) rename skills/{ => preloaded}/openmaic-classroom/references/requirement-builder.md (100%) rename skills/{ => preloaded}/openmaic-classroom/scripts/rag-to-requirement.py (100%) diff --git a/skills/openmaic-classroom/SKILL.md b/skills/preloaded/openmaic-classroom/SKILL.md similarity index 85% rename from skills/openmaic-classroom/SKILL.md rename to skills/preloaded/openmaic-classroom/SKILL.md index c60a7b0e..3acb5dc0 100644 --- a/skills/openmaic-classroom/SKILL.md +++ b/skills/preloaded/openmaic-classroom/SKILL.md @@ -17,8 +17,7 @@ description: 将 RAG 检索结果或文档块转换为 OpenMAIC 互动课程。 > **通过 WeKnora 注册的 mcp-api-requester MCP 工具,你可以直接调用 OpenMAIC API**(HTTP POST/GET 请求)。 > 该工具在 WeKnora agent 中注册为 `mcp_{service_name}_{tool_name}` 格式(如 `mcp_mcp_api_requester_make_request`)。 -> 不再需要向用户提供 curl 命令——直接在后台调用 API 并交付结果。 -> 如果 MCP 工具未配置或不可用,则降级为展示 curl 命令让用户手动执行。 +> **必须**使用该 MCP 工具调用 API。如果 MCP 工具未配置或不可用,引导用户先部署 mcp-api-requester,不提供 curl 命令。 > **⚠️ MCP 可用性检查(每次读取此文件后必须执行):** > 在开始工作前,检查可用的 MCP 工具列表中是否存在名称包含 `mcp_api_requester` 的工具。 @@ -32,13 +31,22 @@ OpenMAIC 有两种使用模式,**根据用户场景选择**: | 模式 | Base URL | 认证方式 | 适用场景 | |------|----------|----------|----------| | 托管模式(推荐快速使用) | `https://open.maic.chat` | `Authorization: Bearer ` | 用户有 open.maic.chat 访问码,无需本地部署 | -| 本地模式 | `http://host.docker.internal:3000`(WeKnora 在容器内)或 `http://localhost:3000`(本地直接运行) | 无认证(本地自部署) | 用户自行部署了 OpenMAIC 实例 | +| 本地模式 | 用户提供(见本地模式 Base URL 处理) | 无认证(本地自部署) | 用户自行部署了 OpenMAIC 实例 | **判断规则**: - 用户提到"在线服务"、"open.maic.chat"、"访问码" → 使用托管模式 - 用户提到"本地部署"、"自建" → 使用本地模式 - 用户未明确说明时,优先询问用户使用哪个模式 +**本地模式 Base URL 处理**: +1. 用户选择本地模式后,必须询问用户:"请输入你的 OpenMAIC 本地部署地址(例如 `http://localhost:3000` 或 `http://192.168.1.100:3000`)" +2. 收到用户提供的地址后,进行如下处理: + - 将地址中的 `127.0.0.1` 替换为 `host.docker.internal` + - 将地址中的 `localhost` 替换为 `host.docker.internal` + - 其他地址保持不变 + +> ⚠️ WeKnora 运行在 Docker 容器内,`localhost` 和 `127.0.0.1` 指向容器自身,无法访问宿主机服务。必须使用 `host.docker.internal` 作为容器访问宿主机的桥接地址。 + ## 前置条件 | 配置项 | 说明 | @@ -121,14 +129,14 @@ execute_skill_script( - 在你可用的 MCP 工具中,找到用于 HTTP 请求的工具 - 工具名称格式为 `mcp_{service_name}_{tool_name}`(如 `mcp_mcp_api_requester_make_request`) - 通过工具描述(description)识别:寻找包含 "HTTP request"、"API"、"GET/POST" 等关键词的工具 -- 如果找不到 HTTP 请求类 MCP 工具,则降级为 curl 方案 +- 如果找不到 HTTP 请求类 MCP 工具,则引导用户部署 mcp-api-requester(见 MCP 可用性检查) **第二步:确定 Base URL 和认证 Header** | 模式 | Base URL | 认证 Header | |------|----------|-------------| | 托管模式 | `https://open.maic.chat` | `Authorization: Bearer ` | -| 本地模式 | `http://host.docker.internal:3000` 或 `http://localhost:3000` | 无 | +| 本地模式 | 用户提供的地址(已将 `localhost`/`127.0.0.1` 替换为 `host.docker.internal`) | 无 | **第三步:Feature Detection(发送可选功能前)** @@ -183,22 +191,11 @@ execute_skill_script( } ``` -**降级方式**:如果 MCP 工具不可用,向用户展示 curl 命令: +**MCP 工具不可用的处理**: -**托管模式**: -```bash -curl -X POST https://open.maic.chat/api/generate-classroom \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{"requirement": "..."}' -``` +告知用户: -**本地模式**: -```bash -curl -X POST /api/generate-classroom \ - -H "Content-Type: application/json" \ - -d '{"requirement": "..."}' -``` +> 未检测到 `mcp_api_requester` MCP 服务。请先从 https://github.com/yryuu/mcp-api-requester 下载代码并部署,然后在 WeKnora 中注册该 MCP 服务。 ### Phase 4: 查询任务进度 @@ -252,7 +249,7 @@ Classroom URL: | 401 | 访问码无效(托管模式) | 告知用户到 open.maic.chat 检查或重新生成访问码 | | 403 | 每日配额用尽(托管模式) | 告知每日 10 次限制,次日零点重置 | | 500 | 服务器错误 | 建议稍后重试或切换到本地模式 | -| Provider 配置错误 | 模型/Provider/认证问题 | 引导用户检查 `.env.local` 或 `server-providers.yml` | +| Provider 配置错误 | 模型/Provider/认证问题 | 引导用户检查 配置或联系管理员 | ## 多文档 → 课程集 @@ -261,15 +258,15 @@ Classroom URL: 1. 收集所有文档内容 2. 为每个文档/主题分别生成 requirement 3. 通过 MCP 工具依次调用生成 API(不可并行,避免配额冲突) -4. 如果 MCP 工具不可用,依次提供对应的 curl 命令 +4. 如果 MCP 工具不可用,告知用户先部署 mcp-api-requester(见 MCP 可用性检查) 5. 汇总返回所有 Classroom URL ## 注意事项 - 脚本在 Docker 沙箱中执行,**沙箱默认禁用网络访问** -- **通过 WeKnora MCP 工具,你可以直接调用 OpenMAIC API**——不再需要用户提供 curl 命令 +- **必须通过 WeKnora MCP 工具调用 OpenMAIC API**——不提供 curl 命令作为降级方案 - MCP 工具名称格式为 `mcp_{service_name}_{tool_name}`,根据描述识别 HTTP 请求工具 -- 如果 MCP 工具未启用或不可用,降级为展示 curl 命令让用户手动执行 +- 如果 MCP 工具未启用或不可用,告知用户先从 https://github.com/yryuu/mcp-api-requester 下载代码并部署,然后在 WeKnora 中注册该 MCP 服务 - 单次生成任务预计 2-10 分钟,取决于内容复杂度和可选功能 - 托管模式(open.maic.chat)每天最多 10 次生成配额,独立于 Web UI 配额 - 如果用户在同一个 job 仍在运行时要求生成新课程,不要重复提交——先检查已有 job 状态 diff --git a/skills/openmaic-classroom/references/api-reference.md b/skills/preloaded/openmaic-classroom/references/api-reference.md similarity index 100% rename from skills/openmaic-classroom/references/api-reference.md rename to skills/preloaded/openmaic-classroom/references/api-reference.md diff --git a/skills/openmaic-classroom/references/requirement-builder.md b/skills/preloaded/openmaic-classroom/references/requirement-builder.md similarity index 100% rename from skills/openmaic-classroom/references/requirement-builder.md rename to skills/preloaded/openmaic-classroom/references/requirement-builder.md diff --git a/skills/openmaic-classroom/scripts/rag-to-requirement.py b/skills/preloaded/openmaic-classroom/scripts/rag-to-requirement.py similarity index 100% rename from skills/openmaic-classroom/scripts/rag-to-requirement.py rename to skills/preloaded/openmaic-classroom/scripts/rag-to-requirement.py From ede7dd08a222b6b52074affe4fed550640cffe13 Mon Sep 17 00:00:00 2001 From: "bingxiang.cheng" Date: Fri, 17 Apr 2026 22:29:37 +0800 Subject: [PATCH 027/192] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=20mcp-api-req?= =?UTF-8?q?uester=20=E4=B8=BA=20mcp=5Fapi=5Frequester=20=E7=9A=84=E5=BC=95?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/preloaded/openmaic-classroom/SKILL.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/skills/preloaded/openmaic-classroom/SKILL.md b/skills/preloaded/openmaic-classroom/SKILL.md index 3acb5dc0..108a0e4f 100644 --- a/skills/preloaded/openmaic-classroom/SKILL.md +++ b/skills/preloaded/openmaic-classroom/SKILL.md @@ -15,7 +15,7 @@ description: 将 RAG 检索结果或文档块转换为 OpenMAIC 互动课程。 ## 能力边界 -> **通过 WeKnora 注册的 mcp-api-requester MCP 工具,你可以直接调用 OpenMAIC API**(HTTP POST/GET 请求)。 +> **通过 WeKnora 注册的 mcp_api_requester MCP 工具,你可以直接调用 OpenMAIC API**(HTTP POST/GET 请求)。 > 该工具在 WeKnora agent 中注册为 `mcp_{service_name}_{tool_name}` 格式(如 `mcp_mcp_api_requester_make_request`)。 > **必须**使用该 MCP 工具调用 API。如果 MCP 工具未配置或不可用,引导用户先部署 mcp-api-requester,不提供 curl 命令。 @@ -129,7 +129,7 @@ execute_skill_script( - 在你可用的 MCP 工具中,找到用于 HTTP 请求的工具 - 工具名称格式为 `mcp_{service_name}_{tool_name}`(如 `mcp_mcp_api_requester_make_request`) - 通过工具描述(description)识别:寻找包含 "HTTP request"、"API"、"GET/POST" 等关键词的工具 -- 如果找不到 HTTP 请求类 MCP 工具,则引导用户部署 mcp-api-requester(见 MCP 可用性检查) +- 如果找不到 HTTP 请求类 MCP 工具,则引导用户部署 mcp_api_requester(见 MCP 可用性检查) **第二步:确定 Base URL 和认证 Header** @@ -258,7 +258,7 @@ Classroom URL: 1. 收集所有文档内容 2. 为每个文档/主题分别生成 requirement 3. 通过 MCP 工具依次调用生成 API(不可并行,避免配额冲突) -4. 如果 MCP 工具不可用,告知用户先部署 mcp-api-requester(见 MCP 可用性检查) +4. 如果 MCP 工具不可用,告知用户先部署 mcp_api_requester(见 MCP 可用性检查) 5. 汇总返回所有 Classroom URL ## 注意事项 From 09e164233557bab7aa81519101843791b78ba6fe Mon Sep 17 00:00:00 2001 From: jw_mac <77239050qq@gmail.com> Date: Mon, 20 Apr 2026 19:14:55 +0800 Subject: [PATCH 028/192] fix(storage): auto-detect content-type to resolve image rendering issues Fixes #995. Added mime type detection in SaveBytes for MinIO, OSS, S3, and TOS to prevent images from being incorrectly saved as text/csv. --- internal/application/service/file/minio.go | 2 +- internal/application/service/file/oss.go | 4 +- internal/application/service/file/s3.go | 56 +--------------------- internal/application/service/file/tos.go | 8 +++- internal/utils/fileutil.go | 53 ++++++++++++++++++++ 5 files changed, 64 insertions(+), 59 deletions(-) create mode 100644 internal/utils/fileutil.go diff --git a/internal/application/service/file/minio.go b/internal/application/service/file/minio.go index f55bff92..e074c9c9 100644 --- a/internal/application/service/file/minio.go +++ b/internal/application/service/file/minio.go @@ -177,7 +177,7 @@ func (s *minioFileService) SaveBytes(ctx context.Context, data []byte, tenantID // Upload bytes to MinIO reader := bytes.NewReader(data) _, err = s.client.PutObject(ctx, s.bucketName, objectName, reader, int64(len(data)), minio.PutObjectOptions{ - ContentType: "text/csv; charset=utf-8", + ContentType: utils.GetContentTypeByExt(ext), }) if err != nil { return "", fmt.Errorf("failed to upload bytes to MinIO: %w", err) diff --git a/internal/application/service/file/oss.go b/internal/application/service/file/oss.go index 1757e2a8..2a1f9038 100644 --- a/internal/application/service/file/oss.go +++ b/internal/application/service/file/oss.go @@ -172,7 +172,7 @@ func (s *ossFileService) SaveFile(ctx context.Context, contentType := file.Header.Get("Content-Type") if contentType == "" { - contentType = getContentTypeByExt(ext) + contentType = utils.GetContentTypeByExt(ext) } // Use Uploader for files > 10MB (auto multipart with concurrent uploads) @@ -233,7 +233,7 @@ func (s *ossFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui Bucket: oss.Ptr(targetBucket), Key: oss.Ptr(objectName), Body: bytes.NewReader(data), - ContentType: oss.Ptr("text/csv; charset=utf-8"), + ContentType: oss.Ptr(utils.GetContentTypeByExt(ext)), }) if err != nil { return "", fmt.Errorf("failed to upload bytes to OSS: %w", err) diff --git a/internal/application/service/file/s3.go b/internal/application/service/file/s3.go index 172cc4bf..38457ab4 100644 --- a/internal/application/service/file/s3.go +++ b/internal/application/service/file/s3.go @@ -172,58 +172,6 @@ func (s *s3FileService) parseS3FilePath(filePath string) (string, error) { return parts[1], nil } -// getContentTypeByExt returns the content type based on file extension -func getContentTypeByExt(ext string) string { - switch strings.ToLower(ext) { - case ".csv": - return "text/csv; charset=utf-8" - case ".json": - return "application/json" - case ".pdf": - return "application/pdf" - case ".doc": - return "application/msword" - case ".docx": - return "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - case ".xls": - return "application/vnd.ms-excel" - case ".xlsx": - return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" - case ".ppt": - return "application/vnd.ms-powerpoint" - case ".pptx": - return "application/vnd.openxmlformats-officedocument.presentationml.presentation" - case ".txt": - return "text/plain; charset=utf-8" - case ".md": - return "text/markdown" - case ".html": - return "text/html; charset=utf-8" - case ".jpg", ".jpeg": - return "image/jpeg" - case ".png": - return "image/png" - case ".gif": - return "image/gif" - case ".svg": - return "image/svg+xml" - case ".mp3": - return "audio/mpeg" - case ".wav": - return "audio/wav" - case ".m4a": - return "audio/mp4" - case ".flac": - return "audio/flac" - case ".ogg": - return "audio/ogg" - case ".mp4": - return "video/mp4" - default: - return "application/octet-stream" - } -} - // SaveFile saves a file to S3 func (s *s3FileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string, @@ -242,7 +190,7 @@ func (s *s3FileService) SaveFile(ctx context.Context, // Determine content type contentType := file.Header.Get("Content-Type") if contentType == "" { - contentType = getContentTypeByExt(ext) + contentType = utils.GetContentTypeByExt(ext) } // Upload file to S3 @@ -313,7 +261,7 @@ func (s *s3FileService) SaveBytes(ctx context.Context, data []byte, tenantID uin Key: aws.String(objectName), Body: reader, ContentLength: aws.Int64(int64(len(data))), - ContentType: aws.String("text/csv; charset=utf-8"), + ContentType: aws.String(utils.GetContentTypeByExt(ext)), }) if err != nil { return "", fmt.Errorf("failed to upload bytes to S3: %w", err) diff --git a/internal/application/service/file/tos.go b/internal/application/service/file/tos.go index df905f44..d4e0cc4e 100644 --- a/internal/application/service/file/tos.go +++ b/internal/application/service/file/tos.go @@ -166,11 +166,15 @@ func (s *tosFileService) SaveFile(ctx context.Context, file *multipart.FileHeade } defer src.Close() + contentType := file.Header.Get("Content-Type") + if contentType == "" { + contentType = utils.GetContentTypeByExt(ext) + } _, err = s.client.PutObjectV2(ctx, &tos.PutObjectV2Input{ PutObjectBasicInput: tos.PutObjectBasicInput{ Bucket: s.bucketName, Key: objectName, - ContentType: file.Header.Get("Content-Type"), + ContentType: contentType, }, Content: src, }) @@ -210,7 +214,7 @@ func (s *tosFileService) SaveBytes(ctx context.Context, data []byte, tenantID ui PutObjectBasicInput: tos.PutObjectBasicInput{ Bucket: targetBucket, Key: objectName, - ContentType: "text/csv; charset=utf-8", + ContentType: utils.GetContentTypeByExt(ext), }, Content: reader, }) diff --git a/internal/utils/fileutil.go b/internal/utils/fileutil.go new file mode 100644 index 00000000..341ddcc0 --- /dev/null +++ b/internal/utils/fileutil.go @@ -0,0 +1,53 @@ +package utils + +import "strings" + +// GetContentTypeByExt returns the content type based on file extension +func GetContentTypeByExt(ext string) string { + switch strings.ToLower(ext) { + case ".csv": + return "text/csv; charset=utf-8" + case ".json": + return "application/json" + case ".pdf": + return "application/pdf" + case ".doc": + return "application/msword" + case ".docx": + return "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + case ".xls": + return "application/vnd.ms-excel" + case ".xlsx": + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + case ".png": + return "image/png" + case ".jpg", ".jpeg": + return "image/jpeg" + case ".gif": + return "image/gif" + case ".webp": + return "image/webp" + case ".svg": + return "image/svg+xml" + case ".txt": + return "text/plain; charset=utf-8" + case ".html", ".htm": + return "text/html; charset=utf-8" + case ".mp4": + return "video/mp4" + case ".mp3": + return "audio/mpeg" + case ".wav": + return "audio/wav" + case ".zip": + return "application/zip" + case ".tar": + return "application/x-tar" + case ".gz": + return "application/gzip" + case ".md": + return "text/markdown; charset=utf-8" + default: + return "application/octet-stream" + } +} From 4ca0c7a644472338a898cfa88283a7dca4240ae0 Mon Sep 17 00:00:00 2001 From: moineye Date: Mon, 20 Apr 2026 22:02:01 +0800 Subject: [PATCH 029/192] fix: ReadEvent incompatible sse data format --- internal/models/chat/sse_reader.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/models/chat/sse_reader.go b/internal/models/chat/sse_reader.go index 6877be27..838c4d8a 100644 --- a/internal/models/chat/sse_reader.go +++ b/internal/models/chat/sse_reader.go @@ -47,6 +47,12 @@ func (r *SSEReader) ReadEvent() (*SSEEvent, error) { return &SSEEvent{Data: []byte(jsonStr)}, nil } + // 增强兼容性(data:后面没有紧接着一个空格) + if strings.HasPrefix(line, "data:") { + jsonStr := line[5:] + return &SSEEvent{Data: []byte(jsonStr)}, nil + } + // 其他行(如 event:, id: 等)跳过 } From 5591c84e7f4d77529e570e1edb1972bc7945e56a Mon Sep 17 00:00:00 2001 From: draix Date: Tue, 21 Apr 2026 09:18:25 -0300 Subject: [PATCH 030/192] fix: remove limit/offset from required in list_knowledge_chunks JSON Schema limit and offset are optional parameters with default values (limit=20, offset=0). Marking them as required in the JSON Schema forces LLM clients to always supply them, breaking calls that rely on the defaults. Fixes #1003 --- internal/agent/tools/list_knowledge_chunks.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/agent/tools/list_knowledge_chunks.go b/internal/agent/tools/list_knowledge_chunks.go index 13633ea2..6c6e9ded 100644 --- a/internal/agent/tools/list_knowledge_chunks.go +++ b/internal/agent/tools/list_knowledge_chunks.go @@ -52,7 +52,7 @@ Full chunk content with chunk_id, chunk_index, and content text.`, "minimum": 0 } }, - "required": ["knowledge_id", "limit", "offset"] + "required": ["knowledge_id"] }`), } From a54822d40269ee2fdb2a62e04c299d08b57cc511 Mon Sep 17 00:00:00 2001 From: Mao Meng <1707647656@qq.com> Date: Tue, 21 Apr 2026 18:16:30 +0800 Subject: [PATCH 031/192] fix/air-toml-cgo-ldflags --- .air.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.air.toml b/.air.toml index cf394665..3700c075 100644 --- a/.air.toml +++ b/.air.toml @@ -5,7 +5,7 @@ tmp_dir = "tmp" [build] args_bin = [] bin = "./tmp/main" - cmd = "CGO_CFLAGS='-Wno-deprecated-declarations -Wno-gnu-folding-constant' CGO_LDFLAGS='-Wl,-no_warn_duplicate_libraries' go build -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server" + cmd = "CGO_CFLAGS='-Wno-deprecated-declarations -Wno-gnu-folding-constant' $(uname | grep -q Darwin && echo \"CGO_LDFLAGS='-Wl,-no_warn_duplicate_libraries'\") go build -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server" delay = 1000 exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs"] exclude_file = [] From da8191cd576ec829747497ae585778cf01feb0cb Mon Sep 17 00:00:00 2001 From: Liwx Date: Tue, 21 Apr 2026 09:44:04 +0800 Subject: [PATCH 032/192] =?UTF-8?q?fix(docker):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E9=95=9C=E5=83=8F=E6=9E=84=E5=BB=BA=E5=85=BC=E5=AE=B9=E6=80=A7?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 7 ++++++- docker/Dockerfile.app | 8 +++++++- docker/Dockerfile.docreader | 35 +++++++++++++++++++++++++++++------ 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index bae931dc..2808f312 100644 --- a/.gitignore +++ b/.gitignore @@ -45,4 +45,9 @@ web/ /server frontend/.vite frontend/chrome-extension/ -WeKnora-Chrome-Extension \ No newline at end of file +WeKnora-Chrome-Extension +packages/protoc-3.19.4-linux-x86_64.zip + +# 本地测试脚本 +configure-ollama.sh +fix-docker.sh \ No newline at end of file diff --git a/docker/Dockerfile.app b/docker/Dockerfile.app index d681cd67..fac4022a 100644 --- a/docker/Dockerfile.app +++ b/docker/Dockerfile.app @@ -57,12 +57,18 @@ ARG APK_MIRROR_ARG # Create a non-root user first RUN useradd -m -s /bin/bash appuser +# First, install ca-certificates without mirror to ensure HTTPS works +RUN apt-get update && \ + apt-get install -y --no-install-recommends ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +# Then switch to mirror if specified and install other packages RUN if [ -n "$APK_MIRROR_ARG" ]; then \ sed -i "s@deb.debian.org@${APK_MIRROR_ARG}@g" /etc/apt/sources.list.d/debian.sources; \ fi && \ apt-get update && \ apt-get install -y --no-install-recommends \ - build-essential postgresql-client default-mysql-client ca-certificates tzdata sed curl bash vim wget \ + build-essential postgresql-client default-mysql-client tzdata sed curl bash vim wget \ libsqlite3-0 \ python3 python3-pip python3-dev libffi-dev libssl-dev \ nodejs npm \ diff --git a/docker/Dockerfile.docreader b/docker/Dockerfile.docreader index cfefb245..c60f7721 100644 --- a/docker/Dockerfile.docreader +++ b/docker/Dockerfile.docreader @@ -29,12 +29,23 @@ RUN apt-get update && apt-get install -y \ # 检查是否存在本地protoc安装包,如果存在则离线安装,否则在线安装 ARG TARGETARCH COPY packages/ /app/packages/ -RUN echo "检查本地protoc安装包..." && \ - case ${TARGETARCH} in \ +# 兼容 BuildKit 和传统构建:如果 TARGETARCH 为空,使用 uname 检测 +RUN if [ -z "$TARGETARCH" ]; then \ + case $(uname -m) in \ + "x86_64") TARGETARCH="amd64" ;; \ + "aarch64") TARGETARCH="arm64" ;; \ + "armv7l") TARGETARCH="arm" ;; \ + *) echo "Unsupported architecture: $(uname -m)" && exit 1 ;; \ + esac; \ + echo "[自动检测] 架构: $TARGETARCH"; \ + else \ + echo "[BuildKit] 架构: $TARGETARCH"; \ + fi && \ + case $TARGETARCH in \ "amd64") PROTOC_ARCH="x86_64" ;; \ "arm64") PROTOC_ARCH="aarch_64" ;; \ "arm") PROTOC_ARCH="arm" ;; \ - *) echo "Unsupported architecture for protoc: ${TARGETARCH}" && exit 1 ;; \ + *) echo "Unsupported architecture for protoc: $TARGETARCH" && exit 1 ;; \ esac && \ PROTOC_PACKAGE="protoc-3.19.4-linux-${PROTOC_ARCH}.zip" && \ if [ -f "/app/packages/${PROTOC_PACKAGE}" ]; then \ @@ -100,12 +111,24 @@ RUN apt-get update && apt-get install -y \ # 安装 grpc_health_probe ARG TARGETARCH -RUN GRPC_HEALTH_PROBE_VERSION=v0.4.24 && \ - case ${TARGETARCH} in \ +# 兼容 BuildKit 和传统构建:如果 TARGETARCH 为空,使用 uname 检测 +RUN if [ -z "$TARGETARCH" ]; then \ + case $(uname -m) in \ + "x86_64") TARGETARCH="amd64" ;; \ + "aarch64") TARGETARCH="arm64" ;; \ + "armv7l") TARGETARCH="arm" ;; \ + *) echo "Unsupported architecture: $(uname -m)" && exit 1 ;; \ + esac; \ + echo "[自动检测] 架构: $TARGETARCH"; \ + else \ + echo "[BuildKit] 架构: $TARGETARCH"; \ + fi && \ + GRPC_HEALTH_PROBE_VERSION=v0.4.24 && \ + case $TARGETARCH in \ "amd64") ARCH="amd64" ;; \ "arm64") ARCH="arm64" ;; \ "arm") ARCH="arm" ;; \ - *) echo "Unsupported architecture: ${TARGETARCH}" && exit 1 ;; \ + *) echo "Unsupported architecture: $TARGETARCH" && exit 1 ;; \ esac && \ wget -qO/bin/grpc_health_probe https://github.com/grpc-ecosystem/grpc-health-probe/releases/download/${GRPC_HEALTH_PROBE_VERSION}/grpc_health_probe-linux-${ARCH} && \ chmod +x /bin/grpc_health_probe From a121a5d636a14411c0cb154bab4dc87b6014619f Mon Sep 17 00:00:00 2001 From: jw_mac <77239050qq@gmail.com> Date: Tue, 21 Apr 2026 23:19:22 +0800 Subject: [PATCH 033/192] =?UTF-8?q?fix(frontend):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=85=AC=E5=BC=8F=E8=BE=93=E5=87=BA=E5=B1=95=E7=A4=BA=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E5=B9=B6=E5=BC=95=E5=85=A5=20KaTeX=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=20(#912)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/package-lock.json | 22 ++++++++++++---- frontend/package.json | 2 ++ frontend/src/components/doc-content.vue | 19 +++++++++++--- frontend/src/components/document-preview.vue | 17 +++++++++++-- frontend/src/utils/security.ts | 9 +++++-- .../chat/components/AgentStreamDisplay.vue | 25 ++++++++++++++++--- frontend/src/views/chat/components/botmsg.vue | 16 +++++++++++- 7 files changed, 93 insertions(+), 17 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 8b6278bf..0644a7ee 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "knowledage-base", - "version": "0.3.6", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "knowledage-base", - "version": "0.3.6", + "version": "0.4.0", "dependencies": { "@microsoft/fetch-event-source": "^2.0.1", "@types/dompurify": "^3.0.5", @@ -16,7 +16,9 @@ "docx-preview": "^0.3.7", "dompurify": "^3.2.6", "highlight.js": "^11.11.1", + "katex": "^0.16.45", "marked": "^17.0.5", + "marked-katex-extension": "^5.1.8", "mermaid": "^11.4.1", "pagefind": "^1.1.1", "papaparse": "^5.5.3", @@ -3774,9 +3776,9 @@ } }, "node_modules/katex": { - "version": "0.16.33", - "resolved": "https://mirrors.tencent.com/npm/katex/-/katex-0.16.33.tgz", - "integrity": "sha512-q3N5u+1sY9Bu7T4nlXoiRBXWfwSefNGoKeOwekV+gw0cAXQlz2Ww6BLcmBxVDeXBMUDQv6fK5bcNaJLxob3ZQA==", + "version": "0.16.45", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.45.tgz", + "integrity": "sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==", "funding": [ "https://opencollective.com/katex", "https://github.com/sponsors/katex" @@ -3961,6 +3963,16 @@ "node": ">= 20" } }, + "node_modules/marked-katex-extension": { + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/marked-katex-extension/-/marked-katex-extension-5.1.8.tgz", + "integrity": "sha512-TsV9OCHHDjVBf4IH0RSjLs4Eqsjj8HGfmVCKlimrS391EtBBxzXj2gBYdF9tY7f7oXu9tb1kHV86ExJsG3iMhw==", + "license": "MIT", + "peerDependencies": { + "katex": ">=0.16 <0.17", + "marked": ">=4 <19" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://mirrors.tencent.com/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index b0d209ca..93c24170 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -20,7 +20,9 @@ "docx-preview": "^0.3.7", "dompurify": "^3.2.6", "highlight.js": "^11.11.1", + "katex": "^0.16.45", "marked": "^17.0.5", + "marked-katex-extension": "^5.1.8", "mermaid": "^11.4.1", "pagefind": "^1.1.1", "papaparse": "^5.5.3", diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index f22c41d8..fdd66177 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -1,6 +1,8 @@ // @ts-nocheck