diff --git a/Makefile b/Makefile index fe488509..239572d1 100644 --- a/Makefile +++ b/Makefile @@ -220,7 +220,7 @@ deps: # Build for production build-prod: - VERSION=$${VERSION:-unknown}; \ + VERSION=$${VERSION:-$$(git describe --tags --abbrev=0 2>/dev/null || echo "unknown")}; \ COMMIT_ID=$${COMMIT_ID:-unknown}; \ BUILD_TIME=$${BUILD_TIME:-unknown}; \ GO_VERSION=$${GO_VERSION:-unknown}; \ diff --git a/client/agent.go b/client/agent.go index 91f8f5b1..f669f4f5 100644 --- a/client/agent.go +++ b/client/agent.go @@ -12,14 +12,26 @@ import ( "strings" ) +// MentionedItem represents a mentioned item in the request +type MentionedItem struct { + ID string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` // "kb" for knowledge base, "file" for file + KBType string `json:"kb_type"` // "document" or "faq" (only for kb type) +} + // AgentQARequest agent Q&A request payload. type AgentQARequest struct { - Query string `json:"query"` // Required query text - KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query - AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode - WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search - SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override - MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list + Query string `json:"query"` // Required query text + KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query + KnowledgeIDs []string `json:"knowledge_ids,omitempty"` // Optional specific knowledge IDs for this query + AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode + AgentID string `json:"agent_id,omitempty"` // Optional custom agent ID + WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search + SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override + MentionedItems []MentionedItem `json:"mentioned_items,omitempty"` // @mentioned knowledge bases and files + DisableTitle bool `json:"disable_title,omitempty"` // Whether to disable auto title generation + MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list (deprecated) } // AgentResponseType defines the type of agent response diff --git a/client/chunk.go b/client/chunk.go index b48fc407..b594efed 100644 --- a/client/chunk.go +++ b/client/chunk.go @@ -15,6 +15,7 @@ import ( // Chunks are the basic units of storage and indexing in the knowledge base type Chunk struct { ID string `json:"id"` // Unique identifier of the chunk + SeqID int64 `json:"seq_id"` // Auto-increment integer ID for external API usage KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base TenantID uint64 `json:"tenant_id"` // Tenant ID diff --git a/client/faq.go b/client/faq.go index 98d05fac..a0fc1fbd 100644 --- a/client/faq.go +++ b/client/faq.go @@ -12,11 +12,11 @@ import ( // FAQEntry represents a FAQ item stored under a knowledge base. type FAQEntry struct { - ID string `json:"id"` + ID int64 `json:"id"` ChunkID string `json:"chunk_id"` KnowledgeID string `json:"knowledge_id"` KnowledgeBaseID string `json:"knowledge_base_id"` - TagID string `json:"tag_id"` + TagID int64 `json:"tag_id"` TagName string `json:"tag_name"` IsEnabled bool `json:"is_enabled"` IsRecommended bool `json:"is_recommended"` @@ -35,12 +35,14 @@ type FAQEntry struct { // FAQEntryPayload is used to create or update a FAQ entry. type FAQEntryPayload struct { + // ID is optional, used for data migration to specify seq_id (must be less than auto-increment start value 100000000) + ID *int64 `json:"id,omitempty"` StandardQuestion string `json:"standard_question"` SimilarQuestions []string `json:"similar_questions,omitempty"` NegativeQuestions []string `json:"negative_questions,omitempty"` Answers []string `json:"answers"` AnswerStrategy *string `json:"answer_strategy,omitempty"` - TagID string `json:"tag_id,omitempty"` + TagID int64 `json:"tag_id,omitempty"` TagName string `json:"tag_name,omitempty"` IsEnabled *bool `json:"is_enabled,omitempty"` IsRecommended *bool `json:"is_recommended,omitempty"` @@ -51,13 +53,15 @@ type FAQBatchUpsertPayload struct { Entries []FAQEntryPayload `json:"entries"` Mode string `json:"mode"` KnowledgeID string `json:"knowledge_id,omitempty"` + TaskID string `json:"task_id,omitempty"` // Optional, if not provided, a UUID will be generated + DryRun bool `json:"dry_run,omitempty"` // If true, only validate without importing } // FAQEntryFieldsUpdate represents the fields that can be updated for a single FAQ entry. type FAQEntryFieldsUpdate struct { - IsEnabled *bool `json:"is_enabled,omitempty"` - IsRecommended *bool `json:"is_recommended,omitempty"` - TagID *string `json:"tag_id,omitempty"` + IsEnabled *bool `json:"is_enabled,omitempty"` + IsRecommended *bool `json:"is_recommended,omitempty"` + TagID *int64 `json:"tag_id,omitempty"` } // FAQEntryFieldsBatchRequest updates multiple fields for FAQ entries in bulk. @@ -65,31 +69,33 @@ type FAQEntryFieldsUpdate struct { // 1. By entry ID: use ByID field // 2. By Tag: use ByTag field to apply the same update to all entries under a tag type FAQEntryFieldsBatchRequest struct { - // ByID updates by entry ID, key is entry ID - ByID map[string]FAQEntryFieldsUpdate `json:"by_id,omitempty"` - // ByTag updates all entries under a tag, key is tag ID (empty string for uncategorized) - ByTag map[string]FAQEntryFieldsUpdate `json:"by_tag,omitempty"` - // ExcludeIDs IDs to exclude from the ByTag update - ExcludeIDs []string `json:"exclude_ids,omitempty"` + // ByID updates by entry ID (seq_id), key is entry seq_id + ByID map[int64]FAQEntryFieldsUpdate `json:"by_id,omitempty"` + // ByTag updates all entries under a tag, key is tag seq_id (0 for uncategorized) + ByTag map[int64]FAQEntryFieldsUpdate `json:"by_tag,omitempty"` + // ExcludeIDs IDs (seq_id) to exclude from the ByTag update + ExcludeIDs []int64 `json:"exclude_ids,omitempty"` } // FAQEntryTagBatchRequest updates tags in bulk. +// key: entry seq_id, value: tag seq_id (nil to remove tag) type FAQEntryTagBatchRequest struct { - Updates map[string]*string `json:"updates"` + Updates map[int64]*int64 `json:"updates"` } // FAQDeleteRequest deletes entries in bulk. type FAQDeleteRequest struct { - IDs []string `json:"ids"` + IDs []int64 `json:"ids"` } // FAQSearchRequest represents the hybrid FAQ search request. type FAQSearchRequest struct { - QueryText string `json:"query_text"` - VectorThreshold float64 `json:"vector_threshold"` - MatchCount int `json:"match_count"` - FirstPriorityTagIDs []string `json:"first_priority_tag_ids"` // First priority tag IDs, highest priority - SecondPriorityTagIDs []string `json:"second_priority_tag_ids"` // Second priority tag IDs, lower than first + QueryText string `json:"query_text"` + VectorThreshold float64 `json:"vector_threshold"` + MatchCount int `json:"match_count"` + FirstPriorityTagIDs []int64 `json:"first_priority_tag_ids"` // First priority tag seq_ids, highest priority + SecondPriorityTagIDs []int64 `json:"second_priority_tag_ids"` // Second priority tag seq_ids, lower than first + OnlyRecommended bool `json:"only_recommended"` // Only return recommended entries } // FAQEntriesPage contains paginated FAQ results. @@ -144,10 +150,11 @@ type faqSimpleResponse struct { } // ListFAQEntries returns paginated FAQ entries under a knowledge base. +// tagSeqID: filter by tag seq_id (0 means no filter) // searchField: specifies which field to search in ("standard_question", "similar_questions", "answers", "" for all) // sortOrder: "asc" for time ascending (updated_at ASC), default is time descending (updated_at DESC) func (c *Client) ListFAQEntries(ctx context.Context, - knowledgeBaseID string, page, pageSize int, tagID string, keyword string, searchField string, sortOrder string, + knowledgeBaseID string, page, pageSize int, tagSeqID int64, keyword string, searchField string, sortOrder string, ) (*FAQEntriesPage, error) { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries", knowledgeBaseID) query := url.Values{} @@ -157,8 +164,8 @@ func (c *Client) ListFAQEntries(ctx context.Context, if pageSize > 0 { query.Add("page_size", strconv.Itoa(pageSize)) } - if tagID != "" { - query.Add("tag_id", tagID) + if tagSeqID != 0 { + query.Add("tag_id", strconv.FormatInt(tagSeqID, 10)) } if keyword != "" { query.Add("keyword", keyword) @@ -222,11 +229,11 @@ func (c *Client) CreateFAQEntry(ctx context.Context, return response.Data, nil } -// GetFAQEntry retrieves a single FAQ entry by ID. +// GetFAQEntry retrieves a single FAQ entry by seq_id. func (c *Client) GetFAQEntry(ctx context.Context, - knowledgeBaseID, entryID string, + knowledgeBaseID string, entrySeqID int64, ) (*FAQEntry, error) { - path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%s", knowledgeBaseID, entryID) + path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%d", knowledgeBaseID, entrySeqID) resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) if err != nil { return nil, err @@ -241,25 +248,51 @@ func (c *Client) GetFAQEntry(ctx context.Context, // UpdateFAQEntry updates a single FAQ entry. func (c *Client) UpdateFAQEntry(ctx context.Context, - knowledgeBaseID, entryID string, payload *FAQEntryPayload, -) error { - path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%s", knowledgeBaseID, entryID) + knowledgeBaseID string, entrySeqID int64, payload *FAQEntryPayload, +) (*FAQEntry, error) { + path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%d", knowledgeBaseID, entrySeqID) resp, err := c.doRequest(ctx, http.MethodPut, path, payload, nil) if err != nil { - return err + return nil, err } - var response faqSimpleResponse - return parseResponse(resp, &response) + var response FAQEntryResponse + if err := parseResponse(resp, &response); err != nil { + return nil, err + } + return response.Data, nil +} + +// AddSimilarQuestionsPayload is used to add similar questions to a FAQ entry. +type AddSimilarQuestionsPayload struct { + SimilarQuestions []string `json:"similar_questions"` +} + +// AddSimilarQuestions adds similar questions to a FAQ entry. +// This will append the new questions to the existing similar questions list. +func (c *Client) AddSimilarQuestions(ctx context.Context, + knowledgeBaseID string, entrySeqID int64, payload *AddSimilarQuestionsPayload, +) (*FAQEntry, error) { + path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%d/similar-questions", knowledgeBaseID, entrySeqID) + resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil) + if err != nil { + return nil, err + } + + var response FAQEntryResponse + if err := parseResponse(resp, &response); err != nil { + return nil, err + } + return response.Data, nil } // UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in bulk. // Supports updating is_enabled, is_recommended, tag_id in a single call. // Supports two modes: -// - byID: update by entry ID, key is entry ID -// - byTag: update all entries under a tag, key is tag ID (empty string for uncategorized) +// - byID: update by entry seq_id, key is entry seq_id +// - byTag: update all entries under a tag, key is tag seq_id (0 for uncategorized) func (c *Client) UpdateFAQEntryFieldsBatch(ctx context.Context, - knowledgeBaseID string, byID map[string]FAQEntryFieldsUpdate, byTag map[string]FAQEntryFieldsUpdate, excludeIDs []string, + knowledgeBaseID string, byID map[int64]FAQEntryFieldsUpdate, byTag map[int64]FAQEntryFieldsUpdate, excludeIDs []int64, ) error { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/fields", knowledgeBaseID) resp, err := c.doRequest(ctx, http.MethodPut, path, &FAQEntryFieldsBatchRequest{ByID: byID, ByTag: byTag, ExcludeIDs: excludeIDs}, nil) @@ -272,8 +305,9 @@ func (c *Client) UpdateFAQEntryFieldsBatch(ctx context.Context, } // UpdateFAQEntryTagBatch updates FAQ entry tags in bulk. +// key: entry seq_id, value: tag seq_id (nil to remove tag) func (c *Client) UpdateFAQEntryTagBatch(ctx context.Context, - knowledgeBaseID string, updates map[string]*string, + knowledgeBaseID string, updates map[int64]*int64, ) error { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/tags", knowledgeBaseID) resp, err := c.doRequest(ctx, http.MethodPut, path, &FAQEntryTagBatchRequest{Updates: updates}, nil) @@ -285,9 +319,9 @@ func (c *Client) UpdateFAQEntryTagBatch(ctx context.Context, return parseResponse(resp, &response) } -// DeleteFAQEntries deletes FAQ entries in bulk. +// DeleteFAQEntries deletes FAQ entries in bulk by seq_id. func (c *Client) DeleteFAQEntries(ctx context.Context, - knowledgeBaseID string, ids []string, + knowledgeBaseID string, ids []int64, ) error { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries", knowledgeBaseID) resp, err := c.doRequest(ctx, http.MethodDelete, path, &FAQDeleteRequest{IDs: ids}, nil) @@ -339,19 +373,55 @@ func (c *Client) ExportFAQEntries(ctx context.Context, knowledgeBaseID string) ( return data, nil } +// FAQFailedEntry represents a failed entry during FAQ import/validation. +type FAQFailedEntry struct { + Index int `json:"index"` + Reason string `json:"reason"` + TagName string `json:"tag_name,omitempty"` + StandardQuestion string `json:"standard_question"` + SimilarQuestions []string `json:"similar_questions,omitempty"` + NegativeQuestions []string `json:"negative_questions,omitempty"` + Answers []string `json:"answers,omitempty"` + AnswerAll bool `json:"answer_all,omitempty"` + IsDisabled bool `json:"is_disabled,omitempty"` +} + +// FAQSuccessEntry represents a successfully imported FAQ entry. +type FAQSuccessEntry struct { + Index int `json:"index"` // Entry index in the batch (0-based) + SeqID int64 `json:"seq_id"` // Entry sequence ID after import + TagID int64 `json:"tag_id,omitempty"` // Tag ID (seq_id) + TagName string `json:"tag_name,omitempty"` // Tag name + StandardQuestion string `json:"standard_question"` // Standard question +} + // FAQImportProgress represents the progress of an async FAQ import task. +// When Status is "completed", the result fields (SkippedCount, ImportMode, ImportedAt, DisplayStatus, ProcessingTime) are populated. type FAQImportProgress struct { - TaskID string `json:"task_id"` - KBID string `json:"kb_id"` - KnowledgeID string `json:"knowledge_id"` - Status string `json:"status"` - Progress int `json:"progress"` - Total int `json:"total"` - Processed int `json:"processed"` - Message string `json:"message"` - Error string `json:"error,omitempty"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` + TaskID string `json:"task_id"` + KBID string `json:"kb_id"` + KnowledgeID string `json:"knowledge_id"` + Status string `json:"status"` + Progress int `json:"progress"` + Total int `json:"total"` + Processed int `json:"processed"` + SuccessCount int `json:"success_count"` + FailedCount int `json:"failed_count"` + SkippedCount int `json:"skipped_count,omitempty"` + FailedEntries []FAQFailedEntry `json:"failed_entries,omitempty"` + SuccessEntries []FAQSuccessEntry `json:"success_entries,omitempty"` // Successfully imported entries (when count is small) + FailedEntriesURL string `json:"failed_entries_url,omitempty"` // CSV download URL when too many failures + Message string `json:"message"` + Error string `json:"error,omitempty"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + DryRun bool `json:"dry_run,omitempty"` // Whether this is a dry run validation + + // Result fields (populated when Status == "completed") + ImportMode string `json:"import_mode,omitempty"` + ImportedAt time.Time `json:"imported_at,omitempty"` + DisplayStatus string `json:"display_status,omitempty"` + ProcessingTime int64 `json:"processing_time,omitempty"` } // FAQImportProgressResponse wraps the FAQ import progress response. @@ -363,6 +433,7 @@ type FAQImportProgressResponse struct { } // GetFAQImportProgress retrieves the progress of an async FAQ import task. +// This works for both regular imports and dry run validations. func (c *Client) GetFAQImportProgress(ctx context.Context, taskID string) (*FAQImportProgress, error) { path := fmt.Sprintf("/api/v1/faq/import/progress/%s", taskID) resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) @@ -376,3 +447,19 @@ func (c *Client) GetFAQImportProgress(ctx context.Context, taskID string) (*FAQI } return response.Data, nil } + +type updateLastFAQImportResultDisplayStatusRequest struct { + DisplayStatus string `json:"display_status"` +} + +// UpdateLastFAQImportResultDisplayStatus updates the display status (open/close) of the last FAQ import result. +func (c *Client) UpdateLastFAQImportResultDisplayStatus(ctx context.Context, knowledgeBaseID string, displayStatus string) error { + path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/import/last-result/display", knowledgeBaseID) + resp, err := c.doRequest(ctx, http.MethodPut, path, &updateLastFAQImportResultDisplayStatusRequest{DisplayStatus: displayStatus}, nil) + if err != nil { + return err + } + + var response faqSimpleResponse + return parseResponse(resp, &response) +} diff --git a/client/tag.go b/client/tag.go index a4e89093..cb0ee353 100644 --- a/client/tag.go +++ b/client/tag.go @@ -12,6 +12,7 @@ import ( // Tag represents a knowledge base tag. type Tag struct { ID string `json:"id"` + SeqID int64 `json:"seq_id"` TenantID uint64 `json:"tenant_id"` KnowledgeBaseID string `json:"knowledge_base_id"` Name string `json:"name"` @@ -121,6 +122,7 @@ func (c *Client) CreateTag(ctx context.Context, } // UpdateTag updates an existing tag. +// tagID can be either UUID or seq_id (as string). func (c *Client) UpdateTag(ctx context.Context, knowledgeBaseID, tagID string, payload *UpdateTagPayload, ) (*Tag, error) { @@ -137,12 +139,20 @@ func (c *Client) UpdateTag(ctx context.Context, return response.Data, nil } +// UpdateTagBySeqID updates an existing tag by seq_id. +func (c *Client) UpdateTagBySeqID(ctx context.Context, + knowledgeBaseID string, tagSeqID int64, payload *UpdateTagPayload, +) (*Tag, error) { + return c.UpdateTag(ctx, knowledgeBaseID, strconv.FormatInt(tagSeqID, 10), payload) +} + // DeleteTag deletes a tag. +// tagID can be either UUID or seq_id (as string). // Set force to true to delete even if the tag is referenced. // Set contentOnly to true to only delete the content under the tag but keep the tag itself. -// excludeIDs: IDs of chunks to exclude from deletion. +// excludeIDs: seq_ids of chunks to exclude from deletion. func (c *Client) DeleteTag(ctx context.Context, - knowledgeBaseID, tagID string, force bool, contentOnly bool, excludeIDs []string, + knowledgeBaseID, tagID string, force bool, contentOnly bool, excludeIDs []int64, ) error { path := fmt.Sprintf("/api/v1/knowledge-bases/%s/tags/%s", knowledgeBaseID, tagID) query := url.Values{} @@ -168,3 +178,10 @@ func (c *Client) DeleteTag(ctx context.Context, var response tagSimpleResponse return parseResponse(resp, &response) } + +// DeleteTagBySeqID deletes a tag by seq_id. +func (c *Client) DeleteTagBySeqID(ctx context.Context, + knowledgeBaseID string, tagSeqID int64, force bool, contentOnly bool, excludeIDs []int64, +) error { + return c.DeleteTag(ctx, knowledgeBaseID, strconv.FormatInt(tagSeqID, 10), force, contentOnly, excludeIDs) +} diff --git a/docreader/parser/base_parser.py b/docreader/parser/base_parser.py index 781830da..f93778d6 100644 --- a/docreader/parser/base_parser.py +++ b/docreader/parser/base_parser.py @@ -55,7 +55,6 @@ class BaseParser(ABC): if not hostname: logger.warning("No hostname found in URL") return False - # Try to parse as IP address try: ip = ipaddress.ip_address(hostname) @@ -743,7 +742,6 @@ class BaseParser(ABC): if not self._is_safe_url(img_url): logger.error(f"URL failed validation check: {img_url}") return img_url, img_url, None - # Still need to get image object for OCR processing # Get proxy settings from environment variables http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY") @@ -794,7 +792,6 @@ class BaseParser(ABC): if not self._is_safe_url(img_url): logger.error(f"URL failed validation check: {img_url}") return img_url, img_url, None - # Get proxy settings from environment variables http_proxy = os.environ.get("EXTERNAL_HTTP_PROXY") https_proxy = os.environ.get("EXTERNAL_HTTPS_PROXY") diff --git a/docs/api/chat.md b/docs/api/chat.md index 3b9a3c1f..4c909627 100644 --- a/docs/api/chat.md +++ b/docs/api/chat.md @@ -50,10 +50,14 @@ Agent 模式支持更智能的问答,包括工具调用、网络搜索、多 **请求参数**: - `query`: 查询文本(必填) - `knowledge_base_ids`: 知识库 ID 数组,可动态指定本次查询使用的知识库(可选) +- `knowledge_ids`: 知识文件 ID 数组,可动态指定本次查询使用的具体知识文件(可选) - `agent_enabled`: 是否启用 Agent 模式(可选,默认 false) +- `agent_id`: 自定义 Agent ID,指定使用的自定义智能体(可选) - `web_search_enabled`: 是否启用网络搜索(可选,默认 false) - `summary_model_id`: 覆盖会话默认的摘要模型 ID(可选) -- `mcp_service_ids`: MCP 服务白名单(可选) +- `mentioned_items`: @提及的知识库和文件列表(可选) +- `disable_title`: 是否禁用自动标题生成(可选,默认 false) +- `mcp_service_ids`: MCP 服务白名单(可选,已废弃) **请求**: @@ -65,7 +69,16 @@ curl --location 'http://localhost:8080/api/v1/agent-chat/ceb9babb-1e30-41d7-817d "query": "帮我查询今天的天气", "agent_enabled": true, "web_search_enabled": true, - "knowledge_base_ids": ["kb-00000001"] + "knowledge_base_ids": ["kb-00000001"], + "agent_id": "agent-001", + "mentioned_items": [ + { + "id": "kb-00000001", + "name": "天气知识库", + "type": "kb", + "kb_type": "document" + } + ] }' ``` diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index 31efab91..614c9631 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -138,16 +138,16 @@ export function updateKnowledgeBaseTag( return put(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}`, data); } -export function deleteKnowledgeBaseTag(kbId: string, tagId: string, params?: { force?: boolean }) { +export function deleteKnowledgeBaseTag(kbId: string, tagSeqId: number, params?: { force?: boolean }) { const forceQuery = params?.force ? '?force=true' : ''; - return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}${forceQuery}`); + return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagSeqId}${forceQuery}`); } export function updateKnowledgeTagBatch(data: { updates: Record }) { return put(`/api/v1/knowledge/tags`, data); } -export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record }) { +export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record }) { return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/tags`, data); } @@ -164,7 +164,7 @@ const buildQuery = (params?: Record) => { export function listFAQEntries( kbId: string, - params?: { page?: number; page_size?: number; tag_id?: string; keyword?: string }, + params?: { page?: number; page_size?: number; tag_id?: number; keyword?: string }, ) { const query = buildQuery(params); return get(`/api/v1/knowledge-bases/${kbId}/faq/entries${query}`); @@ -178,7 +178,7 @@ export function createFAQEntry(kbId: string, data: any) { return post(`/api/v1/knowledge-bases/${kbId}/faq/entry`, data); } -export function updateFAQEntry(kbId: string, entryId: string, data: any) { +export function updateFAQEntry(kbId: string, entryId: number, data: any) { return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data); } @@ -189,19 +189,20 @@ export function updateFAQEntry(kbId: string, entryId: string, data: any) { export interface FAQEntryFieldsUpdate { is_enabled?: boolean is_recommended?: boolean - tag_id?: string | null + tag_id?: number | null } export interface FAQEntryFieldsBatchRequest { - by_id?: Record - by_tag?: Record + by_id?: Record + by_tag?: Record + exclude_ids?: number[] } export function updateFAQEntryFieldsBatch(kbId: string, data: FAQEntryFieldsBatchRequest) { return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/fields`, data); } -export function deleteFAQEntries(kbId: string, ids: string[]) { +export function deleteFAQEntries(kbId: string, ids: number[]) { return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids }); } @@ -223,6 +224,20 @@ export async function exportFAQEntries(kbId: string): Promise { } // FAQ Import Progress API +export interface FAQBlockedEntry { + index: number + standard_question: string + reason: string +} + +export interface FAQSuccessEntry { + index: number + seq_id: number + tag_id?: number + tag_name?: string + standard_question: string +} + export interface FAQImportProgress { task_id: string kb_id: string @@ -231,6 +246,9 @@ export interface FAQImportProgress { progress: number total: number processed: number + blocked: number + blocked_entries?: FAQBlockedEntry[] + success_entries?: FAQSuccessEntry[] message: string error: string created_at: number @@ -241,6 +259,12 @@ export function getFAQImportProgress(taskId: string) { return get(`/api/v1/faq/import/progress/${taskId}`); } +export function updateFAQImportResultDisplayStatus(knowledgeBaseId: string, displayStatus: 'open' | 'close') { + return put(`/api/v1/knowledge-bases/${knowledgeBaseId}/faq/import/last-result/display`, { + display_status: displayStatus + }); +} + export function searchKnowledge(keyword: string, offset = 0, limit = 20, fileTypes?: string[]) { let url = `/api/v1/knowledge/search?keyword=${encodeURIComponent(keyword)}&offset=${offset}&limit=${limit}`; if (fileTypes && fileTypes.length > 0) { diff --git a/frontend/src/components/TenantSelector.vue b/frontend/src/components/TenantSelector.vue index a591c5ae..4be657c8 100644 --- a/frontend/src/components/TenantSelector.vue +++ b/frontend/src/components/TenantSelector.vue @@ -179,12 +179,13 @@ const loadTenants = async (append = false) => { loading.value = true try { - let keyword = searchQuery.value.trim() + const keyword = searchQuery.value.trim() let tenantID: number | undefined = undefined + // 如果是纯数字,同时作为 tenant_id 和 keyword 搜索 + // 这样既能精确匹配租户ID,也能模糊匹配名称中包含数字的租户 if (keyword && /^\d+$/.test(keyword)) { tenantID = Number(keyword) - keyword = '' } const response = await searchTenants({ diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 9c2fbeec..ea47e6d9 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -39,6 +39,7 @@ export default { tagEditSuccess: 'Tag updated', tagDeleteTitle: 'Delete tag', tagDeleteDesc: 'Delete tag "{name}"? All FAQ entries under this tag will also be deleted.', + tagDeleteDescDoc: 'Delete tag "{name}"? All documents under this tag will also be deleted.', tagDeleteSuccess: 'Tag deleted', tagEditAction: 'Rename', tagDeleteAction: 'Delete', @@ -1114,6 +1115,7 @@ export default { questionIndexModeDescription: 'Combined: Standard and similar questions are indexed together. Separate: Each question is indexed independently for more precise retrieval but requires more storage.', entryGuide: 'Each FAQ entry contains a primary question, similar questions, negative examples, and multiple answers. Manage them in the FAQ knowledge base detail view.', tagDesc: 'Select category for FAQ entries', + tagPlaceholder: 'Please select a category', modes: { questionOnly: 'Questions only', questionAnswer: 'Question + answer', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 56571863..f4008c39 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -38,6 +38,7 @@ export default { tagEditSuccess: "태그 업데이트 성공", tagDeleteTitle: "태그 삭제", tagDeleteDesc: '"{name}" 태그를 삭제하시겠습니까? 해당 태그의 모든 FAQ 항목이 함께 삭제됩니다', + tagDeleteDescDoc: '"{name}" 태그를 삭제하시겠습니까? 해당 태그의 모든 문서가 함께 삭제됩니다', tagDeleteSuccess: "태그가 삭제되었습니다", tagEditAction: "이름 변경", tagDeleteAction: "삭제", @@ -1319,6 +1320,7 @@ export default { questionIndexModeDescription: "병합 인덱스: 표준 질문과 유사 질문을 병합 인덱싱; 개별 인덱스: 표준 질문과 각 유사 질문을 독립적으로 인덱싱하여 더 정확하게 검색하지만 더 많은 저장 공간이 필요합니다", entryGuide: "FAQ 항목은 표준 질문, 유사 질문, 반례 및 여러 답변으로 구성됩니다. 지식베이스 세부 정보에서 일괄 가져오기 및 편집할 수 있습니다.", tagDesc: "FAQ 항목에 분류 선택", + tagPlaceholder: "분류를 선택하세요", modes: { questionOnly: "표준 질문/유사 질문만", questionAnswer: "표준 질문 + 답변", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 6ebaa9e7..286b6824 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -38,6 +38,7 @@ export default { tagEditSuccess: 'Тег обновлён', tagDeleteTitle: 'Удаление тега', tagDeleteDesc: 'Удалить тег «{name}»? Все записи FAQ под этим тегом также будут удалены.', + tagDeleteDescDoc: 'Удалить тег «{name}»? Все документы под этим тегом также будут удалены.', tagDeleteSuccess: 'Тег удалён', tagEditAction: 'Переименовать', tagDeleteAction: 'Удалить', @@ -1080,6 +1081,7 @@ export default { questionIndexModeDescription: 'Объединенная: стандартные и похожие вопросы индексируются вместе. Раздельная: каждый вопрос индексируется независимо для более точного поиска, но требует больше места.', entryGuide: 'Каждый FAQ включает основной вопрос, похожие вопросы, негативные примеры и несколько ответов. Управляйте ими в деталях FAQ-базы.', tagDesc: 'Выберите категорию для записей FAQ', + tagPlaceholder: 'Пожалуйста, выберите категорию', modes: { questionOnly: 'Только вопросы', questionAnswer: 'Вопрос + ответ', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 59167c0d..712e6aeb 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -39,6 +39,7 @@ export default { tagEditSuccess: "标签更新成功", tagDeleteTitle: "删除标签", tagDeleteDesc: '确定删除标签"{name}"?该标签下的所有 FAQ 条目将被一并删除', + tagDeleteDescDoc: '确定删除标签"{name}"?该标签下的所有文档将被一并删除', tagDeleteSuccess: "标签已删除", tagEditAction: "重命名", tagDeleteAction: "删除", @@ -1511,6 +1512,7 @@ export default { questionIndexModeDescription: "合并索引:标准问和相似问合并索引;分别索引:标准问和每个相似问独立索引,检索更精确但需要更多存储", entryGuide: "FAQ 条目由标准问、相似问、反例和多个答案组成,可在知识库详情中批量导入、编辑。", tagDesc: "为 FAQ 条目选择分类", + tagPlaceholder: "请选择分类", modes: { questionOnly: "仅标准问/相似问", questionAnswer: "标准问 + 答案", diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 1c01745f..b8046170 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -46,7 +46,7 @@ let knowledgeScroll = ref() let page = 1; let pageSize = 35; -const selectedTagId = ref("__untagged__"); +const selectedTagId = ref(''); const tagList = ref([]); const tagLoading = ref(false); const tagSearchQuery = ref(''); @@ -59,7 +59,6 @@ let tagSearchDebounce: ReturnType | null = null; let docSearchDebounce: ReturnType | null = null; const docSearchKeyword = ref(''); const selectedFileType = ref(''); -const UNTAGGED_TAG_ID = '__untagged__'; const fileTypeOptions = computed(() => [ { content: t('knowledgeBase.allFileTypes') || '全部类型', value: '' }, { content: 'PDF', value: 'pdf' }, @@ -71,18 +70,12 @@ const fileTypeOptions = computed(() => [ { content: t('knowledgeBase.typeManual') || '手动创建', value: 'manual' }, ]); type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>; -const tagDropdownOptions = computed(() => { - const options = [ - { content: t('knowledgeBase.untagged') || '未分类', value: UNTAGGED_TAG_ID }, - ...tagList.value - .filter((tag: any) => tag.id !== UNTAGGED_TAG_ID) - .map((tag: any) => ({ - content: tag.name, - value: tag.id, - })), - ]; - return options; -}); +const tagDropdownOptions = computed(() => + tagList.value.map((tag: any) => ({ + content: tag.name, + value: tag.id, + })), +); const tagMap = computed>(() => { const map: Record = {}; tagList.value.forEach((tag) => { @@ -124,10 +117,9 @@ const getPageSize = () => { getPageSize() // 直接调用 API 获取知识库文件列表 const getTagName = (tagId?: string | number) => { - if (!tagId && tagId !== 0) return t('knowledgeBase.untagged') || '未分类'; - if (tagId === UNTAGGED_TAG_ID) return t('knowledgeBase.untagged') || '未分类'; + if (!tagId && tagId !== 0) return ''; const key = String(tagId); - return tagMap.value[key]?.name || (t('knowledgeBase.untagged') || '未分类'); + return tagMap.value[key]?.name || ''; }; const formatDocTime = (time?: string) => { @@ -227,22 +219,6 @@ const handleTagFilterChange = (value: string) => { }; const handleTagRowClick = (tagId: string) => { - const normalizedId = String(tagId); - if (editingTagId.value && editingTagId.value !== normalizedId) { - editingTagId.value = null; - editingTagName.value = ''; - } - if (creatingTag.value) { - creatingTag.value = false; - newTagName.value = ''; - } - if (selectedTagId.value === normalizedId) { - return; - } - handleTagFilterChange(normalizedId); -}; - -const handleUntaggedClick = () => { if (creatingTag.value) { creatingTag.value = false; newTagName.value = ''; @@ -251,8 +227,8 @@ const handleUntaggedClick = () => { editingTagId.value = null; editingTagName.value = ''; } - if (selectedTagId.value === UNTAGGED_TAG_ID) return; - handleTagFilterChange(UNTAGGED_TAG_ID); + if (selectedTagId.value === tagId) return; + handleTagFilterChange(tagId); }; const startCreateTag = () => { @@ -354,18 +330,24 @@ const confirmDeleteTag = (tag: any) => { if (editingTagId.value) { cancelEditTag(); } + const deleteDescKey = isFAQ.value ? 'knowledgeBase.tagDeleteDesc' : 'knowledgeBase.tagDeleteDescDoc'; const confirm = window.confirm( - t('knowledgeBase.tagDeleteDesc', { name: tag.name }) as string, + t(deleteDescKey, { name: tag.name }) as string, ); if (!confirm) return; - deleteKnowledgeBaseTag(kbId.value, tag.id, { force: true }) + deleteKnowledgeBaseTag(kbId.value, tag.seq_id, { force: true }) .then(() => { MessagePlugin.success(t('knowledgeBase.tagDeleteSuccess')); if (selectedTagId.value === tag.id) { - handleTagFilterChange(UNTAGGED_TAG_ID); + // Reset to show all entries when current tag is deleted + selectedTagId.value = ''; + handleTagFilterChange(''); } loadTags(kbId.value); - loadKnowledgeFiles(kbId.value); + // 由于后端是异步删除文档,延迟刷新以确保看到最新数据 + setTimeout(() => { + loadKnowledgeFiles(kbId.value); + }, 500); }) .catch((error: any) => { MessagePlugin.error(error?.message || t('common.operationFailed')); @@ -374,8 +356,8 @@ const confirmDeleteTag = (tag: any) => { const handleKnowledgeTagChange = async (knowledgeId: string, tagValue: string) => { try { - // When selecting "untagged", pass null to clear the tag - const tagIdToUpdate = tagValue === UNTAGGED_TAG_ID ? null : (tagValue || null); + // Pass the tag value directly (empty string means no tag) + const tagIdToUpdate = tagValue || null; await updateKnowledgeTagBatch({ updates: { [knowledgeId]: tagIdToUpdate } }); MessagePlugin.success(t('knowledgeBase.tagUpdateSuccess') || '分类已更新'); loadKnowledgeFiles(kbId.value); @@ -394,7 +376,7 @@ const loadKnowledgeBaseInfo = async (targetKbId: string) => { try { const res: any = await getKnowledgeBaseById(targetKbId); kbInfo.value = res?.data || null; - selectedTagId.value = UNTAGGED_TAG_ID; + selectedTagId.value = ''; if (!isFAQ.value) { loadKnowledgeFiles(targetKbId); } else { @@ -1053,16 +1035,12 @@ async function createNewSession(value: string): Promise { v-for="tag in filteredTags" :key="tag.id" class="tag-list-item" - :class="{ active: selectedTagId === tag.id, editing: editingTagId === tag.id && tag.id !== UNTAGGED_TAG_ID }" - @click="tag.id === UNTAGGED_TAG_ID ? handleUntaggedClick() : handleTagRowClick(tag.id)" + :class="{ active: selectedTagId === tag.id, editing: editingTagId === tag.id }" + @click="handleTagRowClick(tag.id)" >
- - -