diff --git a/config/prompt_templates/fallback.yaml b/config/prompt_templates/fallback.yaml index 5ae34f83..66036a40 100644 --- a/config/prompt_templates/fallback.yaml +++ b/config/prompt_templates/fallback.yaml @@ -90,12 +90,15 @@ templates: description: "일반 지식을 바탕으로 모델이 답변하도록 안내하는 프롬프트" mode: "model" content: | - No content directly related to the user's question was found in the knowledge base. Please use your general knowledge to help the user answer the question as best as possible. + No content directly matched the user's query via search. However, the knowledge base contains the following documents: + + {{kb_documents}} Important Notes: - 1. Clearly inform the user that this answer is based on general knowledge, not knowledge base content - 2. If the question involves specific domains or requires the latest information, suggest the user consult official resources - 3. Maintain accuracy and objectivity in the response + 1. If the document listing above is available, use it to help answer the user's question (e.g., list relevant documents, suggest which documents may contain the information they need) + 2. If the document listing is empty, use your general knowledge and clearly inform the user that the answer is not from the knowledge base + 3. If the question involves specific domains or requires the latest information, suggest the user consult official resources + 4. Maintain accuracy and objectivity in the response ## CRITICAL: Language Rule - ALWAYS respond in {{language}} @@ -117,10 +120,15 @@ templates: description: "KB에 관련 결과가 없을 때 모델에 위임하는 기본 프롬프트" mode: "model" content: | - You are WeKnora, a professional and friendly AI assistant developed by Tencent. Please answer the user's question based on your knowledge. + You are WeKnora, a professional and friendly AI assistant developed by Tencent. + + No content directly matched the user's query via search. However, the knowledge base contains the following documents: + + {{kb_documents}} ## Response Requirements - - Answer the user's question directly + - If the document listing above is available, use it to help answer the user's question (e.g., list relevant documents, suggest which documents may contain the information they need, or summarize what is available in the knowledge base) + - If the document listing is empty or not relevant, answer the user's question based on your general knowledge and clearly inform the user that the answer is not from the knowledge base - Be concise, clear, and substantive - If real-time data or personal privacy information is involved, honestly state that it cannot be obtained - Use a polite and professional tone diff --git a/config/prompt_templates/rewrite.yaml b/config/prompt_templates/rewrite.yaml index e026f347..d44afe3e 100644 --- a/config/prompt_templates/rewrite.yaml +++ b/config/prompt_templates/rewrite.yaml @@ -32,15 +32,16 @@ templates: - The rewritten question should be within 30 words - IMPORTANT: The rewritten question must be in {{language}} - CRITICAL: The rewritten question will be used for knowledge base retrieval. It MUST preserve specific entities, keywords, and core search terms. Do NOT generate meta-instructions like "请在知识库中查找..." or "请搜索..." — instead, produce a self-contained question that contains the actual search keywords (e.g. person names, concepts, technical terms) + - EXCEPTION to the above: when the user wants to broadly read, browse, organize, or export knowledge base content WITHOUT specifying particular search terms (e.g. "请整理知识库中的数据", "读取知识库中的报告", "列出所有文档"), there are no specific keywords to extract. In this case, keep the original query's key descriptors intact — do NOT strip them as meta-instructions. For example, "请整理知识库中的数据,输出体检指标" should be rewritten as "体检指标数据整理", NOT reduced to "数据". Preserve any mentioned content types (报告/文档), labels (标签名), or file names. ## Task 2: Intent Classification Classify the user's intent into exactly ONE of the following categories. Follow the decision priority below — check from top to bottom, use the FIRST match: 1. `greeting` — Pure greetings, thanks, or farewell with NO substantive question (e.g. "你好", "谢谢", "再见"). - 2. `summarize` — The user asks to summarize, organize, or review the conversation itself (e.g. "总结一下我们的对话"). + 2. `summarize` — The user asks to summarize, organize, or review the **conversation/dialogue itself** (e.g. "总结一下我们的对话", "回顾一下我们聊了什么"). **CRITICAL: If the user mentions "知识库" (knowledge base), documents, files, or reports, it is NOT `summarize` — use `kb_search` instead.** For example, "整理知识库中的数据" is `kb_search`, NOT `summarize`. 3. `web_search` — The question explicitly asks for real-time, latest, or external information unlikely in the knowledge base (e.g. "今天天气怎么样", "最新的新闻"). - 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. "知识库里有这个文件吗", "帮我查一下这个", "能找到相关的资料吗"). + 4. `kb_search` — The user wants to search, find, query, read, browse, organize, list, or extract information from the knowledge base. This includes both specific searches (e.g. "帮我查一下这个") AND broad access requests (e.g. "整理知识库中的数据", "读取知识库中的报告", "列出所有文档"). **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`. 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. "这张图片是什么", "描述一下图片内容", "翻译图中文字"). **CRITICAL: This intent requires `` to be present. If `` appears, NEVER classify as `image_only` — use `kb_search` instead.** @@ -102,6 +103,12 @@ templates: Input: [document attached] "帮我总结一下这份文件" Output: {"rewrite_query":"总结一下这份文件","intent":"doc_only","image_description":""} + Input: "请整理知识库中的数据,用表格形式输出体检指标" (no history) + Output: {"rewrite_query":"体检指标数据整理","intent":"kb_search","image_description":""} + + Input: "请读取知识库中体检报告标签的报告,输出体检指标" (no history) + Output: {"rewrite_query":"体检报告标签 体检指标","intent":"kb_search","image_description":""} + ## Conversation History {{conversation}} user: | diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go index f3ea11ec..e633a050 100644 --- a/internal/application/service/session_knowledge_qa.go +++ b/internal/application/service/session_knowledge_qa.go @@ -767,9 +767,13 @@ func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *t if rq := strings.TrimSpace(chatManage.RewriteQuery); rq != "" { query = rq } + + kbDocuments := s.buildKBDocumentListing(ctx, chatManage) + result := types.RenderPromptPlaceholders(chatManage.FallbackPrompt, types.PlaceholderValues{ - "query": query, - "language": chatManage.Language, + "query": query, + "language": chatManage.Language, + "kb_documents": kbDocuments, }) if chatManage.ImageDescription != "" && !chatManage.ChatModelSupportsVision { @@ -781,6 +785,76 @@ func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *t return result, nil } +// buildKBDocumentListing returns a concise listing of documents in the knowledge bases +// associated with the current pipeline. This gives the LLM visibility into KB contents +// when vector/keyword search returns empty (e.g., broad browse queries). +func (s *sessionService) buildKBDocumentListing(ctx context.Context, chatManage *types.ChatManage) string { + // Collect unique KB IDs from search targets + kbIDs := make(map[string]struct{}) + for _, t := range chatManage.SearchTargets { + kbIDs[t.KnowledgeBaseID] = struct{}{} + } + for _, id := range chatManage.KnowledgeBaseIDs { + kbIDs[id] = struct{}{} + } + if len(kbIDs) == 0 { + return "" + } + + const maxDocuments = 50 + var b strings.Builder + total := 0 + + for kbID := range kbIDs { + if total >= maxDocuments { + break + } + knowledges, err := s.knowledgeService.ListKnowledgeByKnowledgeBaseID(ctx, kbID) + if err != nil { + logger.Warnf(ctx, "buildKBDocumentListing: failed to list knowledge for KB %s: %v", kbID, err) + continue + } + for _, k := range knowledges { + if total >= maxDocuments { + break + } + if k.EnableStatus != "enabled" { + continue + } + title := k.Title + if title == "" { + title = k.FileName + } + if title == "" { + continue + } + fmt.Fprintf(&b, "- %s", title) + if k.FileType != "" { + fmt.Fprintf(&b, " (%s)", k.FileType) + } + if k.Description != "" { + desc := k.Description + if len([]rune(desc)) > 100 { + desc = string([]rune(desc)[:100]) + "..." + } + fmt.Fprintf(&b, ": %s", desc) + } + b.WriteString("\n") + total++ + } + } + + if b.Len() == 0 { + return "" + } + + if total >= maxDocuments { + fmt.Fprintf(&b, "... (showing first %d documents)\n", maxDocuments) + } + + return b.String() +} + // consumeFallbackStream consumes the streaming response and emits events func (s *sessionService) consumeFallbackStream( ctx context.Context,