Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400)

lyingbug2be7bd40631d
diff --git a/client/agent.go b/client/agent.go
index dc6d64f0e..3c70e2303 100644
--- a/client/agent.go
+++ b/client/agent.go
@@ -37,6 +37,7 @@ type AgentQARequest struct {
MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list (deprecated)
Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat
Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
+ QuestionOrigin *QuestionOrigin `json:"question_origin,omitempty"` // Source of a picked suggested question
}
// AgentResponseType defines the type of agent response
diff --git a/client/agent_manage.go b/client/agent_manage.go
index 38d4008a0..21ab8d241 100644
--- a/client/agent_manage.go
+++ b/client/agent_manage.go
@@ -305,6 +305,7 @@ type SuggestedQuestion struct {
Question string `json:"question"` // Question text
Source string `json:"source"` // Source: "faq", "document", or "agent_config"
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"` // Source knowledge base ID
+ KnowledgeID string `json:"knowledge_id,omitempty"` // Source document ID (faq/document sources)
}
// SuggestedQuestionsRequest represents the options for getting suggested questions
diff --git a/client/session.go b/client/session.go
index 31863cea6..39615efaa 100644
--- a/client/session.go
+++ b/client/session.go
@@ -207,18 +207,30 @@ type ImageAttachment struct {
Caption string `json:"caption,omitempty"` // VLM analysis result
}
+// QuestionOrigin names the knowledge source a suggested question was generated
+// from (SuggestedQuestion.KnowledgeBaseID / KnowledgeID). Send it with the
+// question the user picked: the agent searches that source before answering.
+// It is a hint inside the request's retrieval scope and never widens it; for an
+// agent that retrieves only on @mention, it selects the origin base when the
+// agent may read it.
+type QuestionOrigin struct {
+ KnowledgeBaseID string `json:"knowledge_base_id"`
+ KnowledgeID string `json:"knowledge_id,omitempty"`
+}
+
// KnowledgeQARequest knowledge Q&A request
type KnowledgeQARequest struct {
- Query string `json:"query"` // Query text for knowledge base search
- KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base IDs for this request
- KnowledgeIDs []string `json:"knowledge_ids"` // Selected knowledge IDs for this request
- AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
- AgentID string `json:"agent_id"` // Selected custom agent ID for this request
- WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
- SummaryModelID string `json:"summary_model_id"` // Optional summary model ID (overrides session default)
- DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
- Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat
- Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
+ Query string `json:"query"` // Query text for knowledge base search
+ KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base IDs for this request
+ KnowledgeIDs []string `json:"knowledge_ids"` // Selected knowledge IDs for this request
+ AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
+ AgentID string `json:"agent_id"` // Selected custom agent ID for this request
+ WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
+ SummaryModelID string `json:"summary_model_id"` // Optional summary model ID (overrides session default)
+ DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
+ Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat
+ Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
+ QuestionOrigin *QuestionOrigin `json:"question_origin,omitempty"` // Source of a picked suggested question
}
// LLMToolCall represents a function/tool call from the LLM
diff --git a/docs/api/chat.md b/docs/api/chat.md
index 25a8e0cec..b3bb8f56a 100644
--- a/docs/api/chat.md
+++ b/docs/api/chat.md
@@ -37,6 +37,7 @@
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
+| `question_origin` | object | 否 | 用户点选智能体推荐问题(`GET /api/v1/agents/{id}/suggested-questions`)时传入该问题的 `{knowledge_base_id, knowledge_id}`。Agent 会先检索这个来源再作答;它只是本轮检索范围内的提示,不会扩大范围。对仅在 @ 提及时检索知识库的智能体,若该知识库在智能体可用范围内,则本轮检索该知识库 |
**请求**:
@@ -87,6 +88,7 @@ Agent 模式支持更智能的问答,包括工具调用、网络搜索、多
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
+| `question_origin` | object | 否 | 用户点选智能体推荐问题(`GET /api/v1/agents/{id}/suggested-questions`)时传入该问题的 `{knowledge_base_id, knowledge_id}`。Agent 会先检索这个来源再作答;它只是本轮检索范围内的提示,不会扩大范围。对仅在 @ 提及时检索知识库的智能体,若该知识库在智能体可用范围内,则本轮检索该知识库 |
## 回答后推荐问题
diff --git a/docs/docs.go b/docs/docs.go
index ed4fb7a36..3d44c3ad9 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -21545,6 +21545,17 @@ const docTemplate = `{
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.QuestionOrigin": {
+ "type": "object",
+ "properties": {
+ "knowledge_base_id": {
+ "type": "string"
+ },
+ "knowledge_id": {
+ "type": "string"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.QuestionSuggestionConfig": {
"type": "object",
"properties": {
@@ -26187,6 +26198,14 @@ const docTemplate = `{
"description": "Query text for knowledge base search",
"type": "string"
},
+ "question_origin": {
+ "description": "QuestionOrigin is the knowledge source of a picked suggested question.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionOrigin"
+ }
+ ]
+ },
"skill_names": {
"description": "Per-request Skills selected via @mention",
"type": "array",
diff --git a/docs/swagger.json b/docs/swagger.json
index 9e00f227d..be512fe83 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -21538,6 +21538,17 @@
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.QuestionOrigin": {
+ "type": "object",
+ "properties": {
+ "knowledge_base_id": {
+ "type": "string"
+ },
+ "knowledge_id": {
+ "type": "string"
+ }
+ }
+ },
"github_com_Tencent_WeKnora_internal_types.QuestionSuggestionConfig": {
"type": "object",
"properties": {
@@ -26180,6 +26191,14 @@
"description": "Query text for knowledge base search",
"type": "string"
},
+ "question_origin": {
+ "description": "QuestionOrigin is the knowledge source of a picked suggested question.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionOrigin"
+ }
+ ]
+ },
"skill_names": {
"description": "Per-request Skills selected via @mention",
"type": "array",
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index f4c15ebd4..2debbc4fe 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -2930,6 +2930,13 @@ definitions:
10)'
type: integer
type: object
+ github_com_Tencent_WeKnora_internal_types.QuestionOrigin:
+ properties:
+ knowledge_base_id:
+ type: string
+ knowledge_id:
+ type: string
+ type: object
github_com_Tencent_WeKnora_internal_types.QuestionSuggestionConfig:
properties:
follow_ups:
@@ -6423,6 +6430,11 @@ definitions:
query:
description: Query text for knowledge base search
type: string
+ question_origin:
+ allOf:
+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QuestionOrigin'
+ description: QuestionOrigin is the knowledge source of a picked suggested
+ question.
skill_names:
description: Per-request Skills selected via @mention
items:
diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts
index e03c88180..6b12705fa 100644
--- a/frontend/src/api/agent/index.ts
+++ b/frontend/src/api/agent/index.ts
@@ -369,6 +369,7 @@ export interface SuggestedQuestion {
question: string;
source: 'faq' | 'document' | 'agent_config' | 'wiki';
knowledge_base_id?: string;
+ knowledge_id?: string;
}
// 获取智能体推荐问题
diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts
index 3600adfce..eccd3b69b 100644
--- a/frontend/src/api/chat/streame.ts
+++ b/frontend/src/api/chat/streame.ts
@@ -40,7 +40,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
- const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
+ const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const myGeneration = ++streamGeneration
const streamAbort = controller
// 重置状态
@@ -147,6 +147,9 @@ export function useStream() {
if (params.suggestion_attribution) {
postBody.suggestion_attribution = params.suggestion_attribution;
}
+ if (params.question_origin) {
+ postBody.question_origin = params.question_origin;
+ }
postBody.channel = embedToken ? "embed" : "web";
lastStreamRequest.value = {
diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue
index 0ba8265c1..b24366a79 100644
--- a/frontend/src/components/Input-field.vue
+++ b/frontend/src/components/Input-field.vue
@@ -4,6 +4,7 @@ import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { onBeforeRouteUpdate } from 'vue-router';
import { MessagePlugin } from "tdesign-vue-next";
+import type { SendMessageOptions } from '@/utils/questionOrigin';
import { useSettingsStore } from '@/stores/settings';
import { useBrowserConnectionStore } from '@/stores/browserConnection';
import { useUIStore } from '@/stores/ui';
@@ -1948,7 +1949,7 @@ watch([selectedKbIds, selectedFileIds], ([kbIds, fileIds]) => {
}, { deep: true });
const emit = defineEmits<{
- (e: 'send-msg', query: string, modelId: string, mentionedItems: MentionRequestItem[], imageFiles: File[], attachmentFiles: AttachmentFile[]): void;
+ (e: 'send-msg', query: string, modelId: string, mentionedItems: MentionRequestItem[], imageFiles: File[], attachmentFiles: AttachmentFile[], options: SendMessageOptions): void;
(e: 'stop-generation'): void;
(e: 'stop-confirmed'): void;
(e: 'stop-failed'): void;
@@ -1960,7 +1961,13 @@ const emit = defineEmits<{
(e: 'retry-steer', steerId: string): void;
}>();
-const createSession = async (val: string, delivery: 'inject' | 'after' = 'after') => {
+// options ride along with this one send only: a send that returns early (or
+// steers into the running turn) drops them instead of leaving them behind.
+const createSession = async (
+ val: string,
+ delivery: 'inject' | 'after' = 'after',
+ options: SendMessageOptions = {},
+) => {
if (!val.trim()) {
MessagePlugin.info(t('input.messages.enterContent'));
return;
@@ -2017,7 +2024,7 @@ const createSession = async (val: string, delivery: 'inject' | 'after' = 'after'
// Embed 渠道由后端绑定 agent/KB,勿走平台侧 agent 列表与就绪校验
if (props.embeddedMode) {
- emit('send-msg', val, selectedModelId.value || '', [], [], []);
+ emit('send-msg', val, selectedModelId.value || '', [], [], [], options);
clearvalue();
void focusInput();
return;
@@ -2080,7 +2087,7 @@ const createSession = async (val: string, delivery: 'inject' | 'after' = 'after'
const imageFiles = uploadedImages.value.map(img => img.file);
const attachmentFiles = uploadedAttachments.value;
- emit('send-msg', val, selectedModelId.value, mentionedItems, imageFiles, attachmentFiles);
+ emit('send-msg', val, selectedModelId.value, mentionedItems, imageFiles, attachmentFiles, options);
// Clean up image previews
uploadedImages.value.forEach(img => URL.revokeObjectURL(img.preview));
@@ -2610,10 +2617,10 @@ onBeforeRouteUpdate((to, from, next) => {
defineExpose({
focusInput,
- triggerSend(text: string) {
+ triggerSend(text: string, options: SendMessageOptions = {}) {
if (!text.trim()) return;
query.value = text;
- nextTick(() => createSession(text));
+ nextTick(() => createSession(text, 'after', options));
},
/**
* Puts text in the composer WITHOUT sending it. Session fork uses this so
diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts
index 02a481589..c8a439952 100644
--- a/frontend/src/stores/menu.ts
+++ b/frontend/src/stores/menu.ts
@@ -4,6 +4,7 @@ import i18n from '@/i18n'
import { useAuthStore } from '@/stores/auth'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import type { DeploymentCapabilityKey } from '@/config/deploymentCapabilities'
+import type { QuestionOrigin } from '@/utils/questionOrigin'
type MenuChild = Record<string, any>
@@ -44,6 +45,7 @@ export const useMenuStore = defineStore('menuStore', () => {
const firstModelId = ref('')
const firstImageFiles = ref<any[]>([])
const firstAttachmentFiles = ref<any[]>([])
+ const firstQuestionOrigin = ref<QuestionOrigin | null>(null)
const prefillQuery = ref('')
const applyMenuTranslations = () => {
@@ -127,12 +129,13 @@ export const useMenuStore = defineStore('menuStore', () => {
isFirstSession.value = payload
}
- const changeFirstQuery = (payload: string, mentionedItems: any[] = [], modelId: string = '', imageFiles: any[] = [], attachmentFiles: any[] = []) => {
+ const changeFirstQuery = (payload: string, mentionedItems: any[] = [], modelId: string = '', imageFiles: any[] = [], attachmentFiles: any[] = [], questionOrigin: QuestionOrigin | null = null) => {
firstQuery.value = payload
firstMentionedItems.value = mentionedItems
firstModelId.value = modelId
firstImageFiles.value = imageFiles
firstAttachmentFiles.value = attachmentFiles
+ firstQuestionOrigin.value = questionOrigin
}
const setPrefillQuery = (q: string) => {
@@ -154,6 +157,7 @@ export const useMenuStore = defineStore('menuStore', () => {
firstModelId,
firstImageFiles,
firstAttachmentFiles,
+ firstQuestionOrigin,
prefillQuery,
clearMenuArr,
updatemenuArr,
diff --git a/frontend/src/utils/questionOrigin.test.mjs b/frontend/src/utils/questionOrigin.test.mjs
new file mode 100644
index 000000000..00b44fd23
--- /dev/null
+++ b/frontend/src/utils/questionOrigin.test.mjs
@@ -0,0 +1,18 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import { questionOriginFromSuggestion } from './questionOrigin.ts'
+
+test('questionOriginFromSuggestion keeps the knowledge source of a suggestion', () => {
+ assert.deepEqual(
+ questionOriginFromSuggestion({ knowledge_base_id: ' kb-1 ', knowledge_id: ' doc-1 ' }),
+ { knowledge_base_id: 'kb-1', knowledge_id: 'doc-1' },
+ )
+ assert.deepEqual(questionOriginFromSuggestion({ knowledge_base_id: 'kb-2' }), { knowledge_base_id: 'kb-2' })
+})
+
+test('questionOriginFromSuggestion ignores starters without a knowledge source', () => {
+ assert.equal(questionOriginFromSuggestion({}), undefined)
+ assert.equal(questionOriginFromSuggestion({ knowledge_base_id: ' ' }), undefined)
+ assert.equal(questionOriginFromSuggestion(null), undefined)
+})
diff --git a/frontend/src/utils/questionOrigin.ts b/frontend/src/utils/questionOrigin.ts
new file mode 100644
index 000000000..611b51632
--- /dev/null
+++ b/frontend/src/utils/questionOrigin.ts
@@ -0,0 +1,33 @@
+import type { SuggestedQuestion } from '@/api/agent/index'
+
+// The knowledge source a suggested question was generated from. Sent with the
+// picked question so the agent searches that source before answering; the
+// backend treats it as a hint inside the turn's search targets.
+export interface QuestionOrigin {
+ knowledge_base_id: string
+ knowledge_id?: string
+}
+
+// Options bound to one send, carried from the composer to the page that
+// issues the request. Keeping them on the send itself (rather than in shared
+// "pending" state) means a send that never happens, or a second pick before
+// the first one goes out, cannot attach them to the wrong question.
+export interface SendMessageOptions {
+ questionOrigin?: QuestionOrigin
+}
+
+// Agent-authored starters have no knowledge source and yield undefined.
+export function questionOriginFromSuggestion(
+ item: Pick<SuggestedQuestion, 'knowledge_base_id' | 'knowledge_id'> | null | undefined,
+): QuestionOrigin | undefined {
+ const knowledgeBaseId = item?.knowledge_base_id?.trim()
+ if (!item || !knowledgeBaseId) {
+ return undefined
+ }
+ const origin: QuestionOrigin = { knowledge_base_id: knowledgeBaseId }
+ const knowledgeId = item.knowledge_id?.trim()
+ if (knowledgeId) {
+ origin.knowledge_id = knowledgeId
+ }
+ return origin
+}
diff --git a/frontend/src/utils/questionOriginWiring.test.mjs b/frontend/src/utils/questionOriginWiring.test.mjs
new file mode 100644
index 000000000..2b45292ea
--- /dev/null
+++ b/frontend/src/utils/questionOriginWiring.test.mjs
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+
+// A picked suggestion's origin must travel with that one send. Shared
+// "pending" state was lost when a send returned early (agent not ready,
+// upload in progress, steering a running turn) and was overwritten when a
+// second suggestion was picked before the first send went out.
+const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8')
+const inputField = read('../components/Input-field.vue')
+const homePage = read('../views/creatChat/creatChat.vue')
+const chatPage = read('../views/chat/index.vue')
+
+test('the composer forwards send options from triggerSend to send-msg', () => {
+ assert.match(inputField, /triggerSend\(text: string, options: SendMessageOptions = \{\}\)/)
+ assert.match(inputField, /nextTick\(\(\) => createSession\(text, 'after', options\)\)/)
+ const emits = inputField.match(/emit\('send-msg',[^\n]*\)/g) || []
+ assert.ok(emits.length >= 2)
+ for (const call of emits) {
+ assert.match(call, /, options\)$/, `send-msg must forward options: ${call}`)
+ }
+})
+
+test('pages pass the origin through the send instead of shared pending state', () => {
+ for (const [name, source] of [['creatChat.vue', homePage], ['chat/index.vue', chatPage]]) {
+ assert.doesNotMatch(source, /pendingQuestionOrigin/, `${name} must not keep a pending origin`)
+ assert.match(source, /triggerSend\(item\.question, \{ questionOrigin: questionOriginFromSuggestion\(item\) \}\)|triggerSend\(item\.question, options\)/, name)
+ }
+ assert.match(homePage, /changeFirstQuery\([^)]*options\.questionOrigin \?\? null\)/)
+ assert.match(chatPage, /@send-msg="\([^"]*options\) => sendMsg\([^"]*options\)"/)
+ assert.match(chatPage, /question_origin: options\?\.questionOrigin/)
+ assert.match(chatPage, /questionOrigin: firstQuestionOrigin\.value \|\| undefined/)
+})
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 8e8e28d1f..29fde475b 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -80,7 +80,7 @@
<div class="suggested-questions-grid">
<div v-for="(item, index) in suggestedQuestions" :key="item.question"
class="suggested-question-card"
- @click="handleSuggestedQuestionClick(item.question)">
+ @click="handleSuggestedQuestionClick(item)">
<span class="suggested-question-text">{{ item.question }}</span>
<span v-if="item.source === 'faq'"
class="suggested-question-badge faq">FAQ</span>
@@ -155,7 +155,7 @@
</transition>
<div class="input-container" :class="{ 'is-embedded': embeddedMode }">
<InputField ref="inputFieldRef" :auto-focus="focusComposerOnMount"
- @send-msg="(query, modelId, mentionedItems, imageFiles, attachmentFiles) => sendMsg(query, modelId, mentionedItems, imageFiles, attachmentFiles)"
+ @send-msg="(query, modelId, mentionedItems, imageFiles, attachmentFiles, options) => sendMsg(query, modelId, mentionedItems, imageFiles, attachmentFiles, options)"
@steer-msg="(query, mentionedItems, delivery) => handleSteerMsg(query, mentionedItems, delivery)"
@promote-steer="handlePromoteSteer"
@remove-steer="handleRemoveSteer"
@@ -189,6 +189,7 @@ import usermsg from './components/usermsg.vue';
import { getMessageList, getSession, forkSession } from "@/api/chat/index";
import { resolveForkAffordance } from './forkPoint';
import { getSuggestedQuestions } from "@/api/agent/index";
+import { questionOriginFromSuggestion } from '@/utils/questionOrigin';
import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments';
import { useStream } from '../../api/chat/streame'
import { listSteerSession, promoteSteerSession, removeSteerSession, steerSession } from '@/api/chat/steer';
@@ -254,7 +255,7 @@ const isAgentStreamSession = () => {
const uiStore = useUIStore();
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
const { t } = useI18n();
-const { firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles } = storeToRefs(usemenuStore);
+const { firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles, firstQuestionOrigin } = storeToRefs(usemenuStore);
// Capture before the initial send consumes firstQuery; the child focuses after mounting.
const focusComposerOnMount = Boolean(firstQuery.value);
const { onChunk, error, isStreaming, startStream, stopStream, lastStreamRequest } = useStream();
@@ -545,11 +546,13 @@ const fetchSuggestedQuestions = async () => {
}
};
-const handleSuggestedQuestionClick = (question) => {
+// The suggestion's source rides with this send only, as a retrieval hint.
+const handleSuggestedQuestionClick = (item) => {
+ const options = { questionOrigin: questionOriginFromSuggestion(item) };
if (inputFieldRef.value?.triggerSend) {
- inputFieldRef.value.triggerSend(question);
+ inputFieldRef.value.triggerSend(item.question, options);
} else {
- sendMsg(question);
+ sendMsg(item.question, '', [], [], [], options);
}
};
@@ -1221,7 +1224,7 @@ const attachSteerFollowUp = async (completedAssistantId) => {
}
};
-const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = []) => {
+const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = [], options = {}) => {
stopStream();
prepareForNewOutgoingMessage();
activitySessionId.value = String(session_id.value);
@@ -1400,6 +1403,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
attachment_ids: attachmentIds.length > 0 ? attachmentIds : undefined,
query: value,
suggestion_attribution: suggestionAttribution || undefined,
+ question_origin: options?.questionOrigin,
method: 'POST',
url: endpoint,
});
@@ -1548,7 +1552,7 @@ onMounted(async () => {
rerankModelId: '',
});
}
- sendMsg(firstQuery.value, firstModelId.value || '', firstMentionedItems.value || [], firstImageFiles.value || [], firstAttachmentFiles.value || []);
+ sendMsg(firstQuery.value, firstModelId.value || '', firstMentionedItems.value || [], firstImageFiles.value || [], firstAttachmentFiles.value || [], { questionOrigin: firstQuestionOrigin.value || undefined });
usemenuStore.changeFirstQuery('', [], '', [], []);
} else {
scrollLock.value = false;
diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue
index 2abbf832a..abddf8663 100644
--- a/frontend/src/views/creatChat/creatChat.vue
+++ b/frontend/src/views/creatChat/creatChat.vue
@@ -35,7 +35,7 @@
<div v-for="(item, index) in suggestedQuestions" :key="item.question"
class="suggested-question-card" :class="{ 'sq-card-visible': sqCardsRevealed }"
:style="{ transitionDelay: sqCardsRevealed ? `${index * 50}ms` : '0ms' }"
- @click="handleSuggestedQuestionClick(item.question)">
+ @click="handleSuggestedQuestionClick(item)">
<span class="suggested-question-text">{{ item.question }}</span>
<span v-if="item.source === 'faq'" class="suggested-question-badge faq">FAQ</span>
</div>
@@ -61,6 +61,7 @@ import InputField from '@/components/Input-field.vue';
import { createSessions } from "@/api/chat/index";
import { getSuggestedQuestions } from "@/api/agent/index";
import type { SuggestedQuestion } from "@/api/agent/index";
+import { questionOriginFromSuggestion, type SendMessageOptions } from '@/utils/questionOrigin';
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
import { useUIStore } from '@/stores/ui';
@@ -181,15 +182,17 @@ onMounted(() => { fetchSuggestedQuestions(); });
const inputFieldRef = ref();
-const handleSuggestedQuestionClick = (question: string) => {
- inputFieldRef.value?.triggerSend(question);
+// The suggestion's source rides with this send to the new session's first
+// request, so the agent searches it before answering.
+const handleSuggestedQuestionClick = (item: SuggestedQuestion) => {
+ inputFieldRef.value?.triggerSend(item.question, { questionOrigin: questionOriginFromSuggestion(item) });
};
-const sendMsg = (value: string, modelId: string, mentionedItems: any[], imageFiles: any[] = [], attachmentFiles: any[] = []) => {
- createNewSession(value, modelId, mentionedItems, imageFiles, attachmentFiles);
+const sendMsg = (value: string, modelId: string, mentionedItems: any[], imageFiles: any[] = [], attachmentFiles: any[] = [], options: SendMessageOptions = {}) => {
+ createNewSession(value, modelId, mentionedItems, imageFiles, attachmentFiles, options);
}
-async function createNewSession(value: string, modelId: string, mentionedItems: any[] = [], imageFiles: any[] = [], attachmentFiles: any[] = []) {
+async function createNewSession(value: string, modelId: string, mentionedItems: any[] = [], imageFiles: any[] = [], attachmentFiles: any[] = [], options: SendMessageOptions = {}) {
const selectedKbs = settingsStore.settings.selectedKnowledgeBases || [];
const selectedFiles = settingsStore.settings.selectedFiles || [];
@@ -209,7 +212,7 @@ async function createNewSession(value: string, modelId: string, mentionedItems:
try {
const res = await createSessions(sessionData);
if (res.data && res.data.id) {
- await navigateToSession(res.data.id, value, modelId, mentionedItems, imageFiles, attachmentFiles);
+ await navigateToSession(res.data.id, value, modelId, mentionedItems, imageFiles, attachmentFiles, options);
} else {
console.error('[createChat] Failed to create session');
MessagePlugin.error(t('createChat.messages.createFailed'));
@@ -220,7 +223,7 @@ async function createNewSession(value: string, modelId: string, mentionedItems:
}
}
-const navigateToSession = async (sessionId: string, value: string, modelId: string, mentionedItems: any[], imageFiles: any[] = [], attachmentFiles: any[] = []) => {
+const navigateToSession = async (sessionId: string, value: string, modelId: string, mentionedItems: any[], imageFiles: any[] = [], attachmentFiles: any[] = [], options: SendMessageOptions = {}) => {
const now = new Date().toISOString();
let obj = {
title: t('createChat.newSessionTitle'),
@@ -233,7 +236,7 @@ const navigateToSession = async (sessionId: string, value: string, modelId: stri
};
usemenuStore.updataMenuChildren(obj);
usemenuStore.changeIsFirstSession(true);
- usemenuStore.changeFirstQuery(value, mentionedItems, modelId, imageFiles, attachmentFiles);
+ usemenuStore.changeFirstQuery(value, mentionedItems, modelId, imageFiles, attachmentFiles, options.questionOrigin ?? null);
router.push(`/platform/chat/${sessionId}`);
}
diff --git a/internal/agent/engine.go b/internal/agent/engine.go
index 879cfee43..2baa773e4 100644
--- a/internal/agent/engine.go
+++ b/internal/agent/engine.go
@@ -41,6 +41,7 @@ type AgentEngine struct {
selectedDocs []*SelectedDocumentInfo // User-selected documents (via @ mention)
pinnedMCPServices []*PinnedMCPServiceInfo // User @mentioned MCP services for this turn
pinnedSkills []*PinnedSkillInfo // User @mentioned skills for this turn
+ questionOrigin *QuestionOriginInfo // Source of a picked suggested question, if any
sessionID string // Session ID for logging and event emission
systemPromptTemplate string // System prompt template (optional, uses default if empty)
memoryPrompt string // Long-term memory envelope appended to the system prompt
@@ -119,6 +120,12 @@ func NewAgentEngine(
return engine
}
+// SetQuestionOrigin records the knowledge source of a suggested question the
+// user picked for this turn; nil clears it.
+func (e *AgentEngine) SetQuestionOrigin(origin *QuestionOriginInfo) {
+ e.questionOrigin = origin
+}
+
// SetPinnedMentions sets per-turn @mention scope for MCP services and skills.
func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) {
e.pinnedMCPServices = mcpServices
diff --git a/internal/agent/grounding_prompt.go b/internal/agent/grounding_prompt.go
index a36d4614e..10552268b 100644
--- a/internal/agent/grounding_prompt.go
+++ b/internal/agent/grounding_prompt.go
@@ -43,11 +43,13 @@ func formatGroundingGuidance(names []string) string {
}
if len(kbTools) > 0 {
b.WriteString("- Available knowledge tools: " + strings.Join(kbTools, ", ") +
- ". Consult the current runtime_context scope and capabilities. When no source was " +
- "explicitly selected, use relevant bound knowledge bases for factual tasks. With an " +
- "explicit source selection, KB retrieval is complementary, not a prerequisite. Directory " +
- "entries are routing hints, not retrieved evidence; do not exhaust unrelated bases. " +
- "Choose an available search or reader appropriate to the scope.\n")
+ ". Consult the current runtime_context scope and capabilities. When knowledge bases are " +
+ "bound, search them before answering a question about a topic, even one that reads like " +
+ "general knowledge: the user may mean what their documents say, and directory profiles " +
+ "and recent titles show only a sample, so they cannot prove a base lacks the answer. " +
+ "With an explicit source selection, KB retrieval is complementary, not a prerequisite. " +
+ "Directory entries are routing hints, not retrieved evidence; do not exhaust unrelated " +
+ "bases. Choose an available search or reader appropriate to the scope.\n")
}
if slices.Contains(names, tools.ToolWebSearch) {
b.WriteString("- web_search is available: use it when relevant local evidence is missing, " +
@@ -68,13 +70,14 @@ func formatGroundingGuidance(names []string) string {
b.WriteString("- Use only resources accessible through this turn's tools and supplied context. " +
"If relevant sources are unavailable or searches leave gaps, state a limitation only when it " +
"affects the answer and distinguish unverified background knowledge from supported claims. Do " +
- "not invent sources, claim a search you did not perform, or treat a failed/empty lookup as " +
- "verification. Ask for missing material only when needed to complete the task accurately.\n")
+ "not invent sources or treat a failed/empty lookup as verification, and say you searched or " +
+ "found nothing only when a search tool actually ran for this task. Ask for missing material " +
+ "only when needed to complete the task accurately.\n")
b.WriteString("- Direct conversation, creative writing, and translation or formatting of supplied " +
- "content do not require research unless you add factual claims. Stable general explanations " +
- "need no lookup unless the task depends on specific source content or uncertain details. If " +
- "the user explicitly limits sources or requests no research, respect that and identify " +
- "material uncertainty. Stop searching once evidence is sufficient.\n")
+ "content do not require research unless you add factual claims. Without bound knowledge bases, " +
+ "stable general explanations need no lookup unless the task depends on specific source " +
+ "content or uncertain details. If the user explicitly limits sources or requests no research, " +
+ "respect that and identify material uncertainty. Stop searching once evidence is sufficient.\n")
b.WriteString("- Check both content support and artifact execution before reporting completion. " +
"Preserve source titles/URLs and relevant limitations in factual deliverables where " +
"appropriate; a generated file's existence only verifies generation, not its accuracy. Treat " +
diff --git a/internal/agent/grounding_prompt_test.go b/internal/agent/grounding_prompt_test.go
index 3eade98ab..487f2e0ad 100644
--- a/internal/agent/grounding_prompt_test.go
+++ b/internal/agent/grounding_prompt_test.go
@@ -58,13 +58,19 @@ func TestGroundingUsesRegistryInsteadOfConfiguration(t *testing.T) {
[]string{tools.ToolReadFile, tools.ToolShellExec},
true,
nil,
- []string{"Available knowledge tools:", "web_search is available", "web_fetch is available"},
+ []string{
+ "Available knowledge tools:", "web_search is available", "web_fetch is available",
+ "search them before answering",
+ },
},
{
"rag",
[]string{tools.ToolSearchKnowledge, tools.ToolReadDocument},
false,
- []string{"Available knowledge tools: search_knowledge, read_document"},
+ []string{
+ "Available knowledge tools: search_knowledge, read_document",
+ "search them before answering a question about a topic, even one that reads like general knowledge",
+ },
[]string{"wiki_search", "web_search is available"},
},
{
diff --git a/internal/agent/observe.go b/internal/agent/observe.go
index f1ede12f7..80955a21e 100644
--- a/internal/agent/observe.go
+++ b/internal/agent/observe.go
@@ -522,6 +522,7 @@ func buildRuntimeContextBlock(
sessionID string,
kbs []*KnowledgeBaseInfo,
docs []*SelectedDocumentInfo,
+ origin *QuestionOriginInfo,
) string {
var sb strings.Builder
sb.WriteString("<runtime_context scope=\"this_turn\">\n")
@@ -564,10 +565,40 @@ func buildRuntimeContextBlock(
sb.WriteString(" </pinned_documents>\n")
}
+ writeQuestionOrigin(&sb, origin)
+
sb.WriteString("</runtime_context>")
return sb.String()
}
+// writeQuestionOrigin tells the model which source a picked suggested
+// question came from. Such a question is phrased from one document's
+// content, so it can read like general knowledge ("why be careful comparing
+// graphs?") while meaning something specific to that document; without the
+// hint the model may answer from memory without searching at all.
+func writeQuestionOrigin(sb *strings.Builder, origin *QuestionOriginInfo) {
+ if origin == nil || origin.KnowledgeBaseID == "" {
+ return
+ }
+ fmt.Fprintf(sb, " <question_origin knowledge_base_id=\"%s\"", escapeXMLAttr(origin.KnowledgeBaseID))
+ if origin.KnowledgeBaseName != "" {
+ fmt.Fprintf(sb, " name=\"%s\"", escapeXMLAttr(origin.KnowledgeBaseName))
+ }
+ sb.WriteString(">\n")
+ if d := origin.Document; d != nil && d.KnowledgeID != "" {
+ title := d.Title
+ if title == "" {
+ title = d.FileName
+ }
+ fmt.Fprintf(sb, " <document knowledge_id=\"%s\" title=\"%s\" />\n",
+ escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title))
+ }
+ sb.WriteString(" <note>The user picked this question from suggestions generated from this source. " +
+ "Search it before answering: the question refers to that content even when it reads like " +
+ "general knowledge.</note>\n")
+ sb.WriteString(" </question_origin>\n")
+}
+
// buildMustUseBlock emits a short per-turn hint when the user @mentioned MCP/Skill.
// Tool names are not listed here — they are already in the function-calling schema.
func buildMustUseBlock(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) string {
@@ -690,7 +721,7 @@ func commonStringPrefix(a, b string) string {
// not written to rendered_content / history.
func (e *AgentEngine) RenderUserTurnContent(sessionID, query string) string {
e.registerRuntimeReferences()
- runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
+ runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs, e.questionOrigin)
runtimeCtx = e.modelContext.CompactKnownText(runtimeCtx)
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
return composeUserTurnContent(runtimeCtx, mustUse, query)
@@ -731,6 +762,12 @@ func (e *AgentEngine) registerRuntimeReferences() {
e.modelContext.RegisterDocument(doc.KnowledgeID)
e.modelContext.RegisterKnowledgeBase(doc.KnowledgeBaseID)
}
+ if origin := e.questionOrigin; origin != nil {
+ e.modelContext.RegisterKnowledgeBase(origin.KnowledgeBaseID)
+ if origin.Document != nil {
+ e.modelContext.RegisterDocument(origin.Document.KnowledgeID)
+ }
+ }
}
func firstNonEmptyAgent(values ...string) string {
diff --git a/internal/agent/observe_test.go b/internal/agent/observe_test.go
index 4ae42d472..c2f19df76 100644
--- a/internal/agent/observe_test.go
+++ b/internal/agent/observe_test.go
@@ -247,6 +247,7 @@ func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
Title: "Report.pdf",
FileType: "pdf",
}},
+ nil,
)
assert.Contains(t, block, "<pinned_documents")
@@ -258,6 +259,43 @@ func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
assert.NotContains(t, block, "<must_use>")
}
+func TestBuildRuntimeContextBlock_QuestionOrigin(t *testing.T) {
+ origin := &QuestionOriginInfo{
+ KnowledgeBaseID: "kb-1",
+ KnowledgeBaseName: "TEST",
+ Document: &SelectedDocumentInfo{KnowledgeID: "kid-1", Title: "Corners <SSAO>"},
+ }
+ block := buildRuntimeContextBlock("sess-1", nil, nil, origin)
+ assert.Contains(t, block, `<question_origin knowledge_base_id="kb-1" name="TEST">`)
+ assert.Contains(t, block, `<document knowledge_id="kid-1" title="Corners &lt;SSAO&gt;" />`)
+ assert.Contains(t, block, "Search it before answering")
+
+ baseOnly := buildRuntimeContextBlock("sess-1", nil, nil, &QuestionOriginInfo{KnowledgeBaseID: "kb-1"})
+ assert.Contains(t, baseOnly, `<question_origin knowledge_base_id="kb-1">`, "an unknown name is omitted, not empty")
+ assert.NotContains(t, baseOnly, "<document")
+
+ assert.NotContains(t, buildRuntimeContextBlock("sess-1", nil, nil, nil), "question_origin")
+}
+
+// The origin's raw IDs must reach the model as handles it can pass to
+// search_knowledge / read_document, never as durable IDs.
+func TestRenderUserTurnContent_QuestionOriginUsesHandles(t *testing.T) {
+ engine := &AgentEngine{
+ modelContext: modelcontext.NewRegistry(true),
+ knowledgeBasesInfo: []*KnowledgeBaseInfo{{ID: "kb-real-id", Name: "TEST"}},
+ questionOrigin: &QuestionOriginInfo{
+ KnowledgeBaseID: "kb-real-id",
+ KnowledgeBaseName: "TEST",
+ Document: &SelectedDocumentInfo{KnowledgeID: "doc-real-id", Title: "Corners"},
+ },
+ }
+ out := engine.RenderUserTurnContent("sess-1", "为什么在比较图形时需要谨慎处理?")
+ assert.Contains(t, out, `<question_origin knowledge_base_id="b1" name="TEST">`)
+ assert.Contains(t, out, `<document knowledge_id="d1" title="Corners" />`)
+ assert.NotContains(t, out, "kb-real-id")
+ assert.NotContains(t, out, "doc-real-id")
+}
+
func TestBuildMustUseBlock_MCPAndSkills(t *testing.T) {
block := buildMustUseBlock(
[]*PinnedMCPServiceInfo{{
diff --git a/internal/agent/prompt_composition_test.go b/internal/agent/prompt_composition_test.go
index ed0e518c4..9e560133a 100644
--- a/internal/agent/prompt_composition_test.go
+++ b/internal/agent/prompt_composition_test.go
@@ -89,7 +89,7 @@ func TestRuntimeDirectoryEscapesAndBoundsUntrustedContent(t *testing.T) {
}
require.NoError(t, err, "untrusted values must not break the directory envelope")
}
- context := buildRuntimeContextBlock("session", kbs, nil)
+ context := buildRuntimeContextBlock("session", kbs, nil, nil)
require.NotContains(t, context, "<communication_instruction>")
require.NotContains(t, context, "<answer_instruction>")
}
diff --git a/internal/agent/prompts.go b/internal/agent/prompts.go
index 4909f65fe..b549a5096 100644
--- a/internal/agent/prompts.go
+++ b/internal/agent/prompts.go
@@ -54,6 +54,15 @@ type SelectedDocumentInfo struct {
FileType string // File type (pdf, docx, etc.)
}
+// QuestionOriginInfo is the knowledge source a suggested question was
+// generated from, when the user picked that question. Rendered into
+// runtime_context so the model searches the source before answering.
+type QuestionOriginInfo struct {
+ KnowledgeBaseID string
+ KnowledgeBaseName string
+ Document *SelectedDocumentInfo // nil when only the base is known
+}
+
// PinnedMCPServiceInfo describes an MCP service explicitly @mentioned for this turn.
type PinnedMCPServiceInfo struct {
Discoverable bool // Available through the scoped MCP directory.
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go
index a59ccb0f4..da08feb4c 100644
--- a/internal/application/service/agent_service.go
+++ b/internal/application/service/agent_service.go
@@ -242,6 +242,7 @@ func (s *agentService) CreateAgentEngine(
pinnedMCP,
s.resolvePinnedSkillInfos(config),
)
+ engine.SetQuestionOrigin(s.resolveQuestionOriginInfo(ctx, config.QuestionOrigin, config.SearchTargets, kbInfos))
// Non-vision chat models use the configured VLM to describe tool images.
// Vision chat models receive the original images after the tool replies.
@@ -1343,6 +1344,45 @@ func kbRetrievalCapabilities(kb *types.KnowledgeBase) []string {
// getSelectedDocumentInfos retrieves detailed information for user-selected documents (via @ mention)
// This loads the actual content of the documents to include in the system prompt
+// resolveQuestionOriginInfo turns a suggested question's origin into the
+// names the runtime context shows. It re-checks the base against this turn's
+// search targets rather than trusting the caller, and keeps a document only
+// when it belongs to that base. A base reached only through a document or tag
+// scope is not in kbInfos when other bases are selected, so its name is
+// looked up directly.
+func (s *agentService) resolveQuestionOriginInfo(
+ ctx context.Context, origin *types.QuestionOrigin, targets types.SearchTargets,
+ kbInfos []*agent.KnowledgeBaseInfo,
+) *agent.QuestionOriginInfo {
+ if origin == nil || origin.KnowledgeBaseID == "" || !targets.ContainsKB(origin.KnowledgeBaseID) {
+ return nil
+ }
+ info := &agent.QuestionOriginInfo{KnowledgeBaseID: origin.KnowledgeBaseID}
+ for _, kb := range kbInfos {
+ if kb != nil && kb.ID == origin.KnowledgeBaseID {
+ info.KnowledgeBaseName = kb.Name
+ break
+ }
+ }
+ if info.KnowledgeBaseName == "" && s.knowledgeBaseService != nil {
+ kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, origin.KnowledgeBaseID)
+ if err == nil && kb != nil {
+ info.KnowledgeBaseName = kb.Name
+ }
+ }
+ if origin.KnowledgeID == "" {
+ return info
+ }
+ docs, err := s.getSelectedDocumentInfos(ctx, []string{origin.KnowledgeID})
+ if err != nil || len(docs) != 1 || docs[0].KnowledgeBaseID != origin.KnowledgeBaseID {
+ logger.Infof(ctx, "Question origin document %s dropped: not found in knowledge base %s",
+ secutils.SanitizeForLog(origin.KnowledgeID), secutils.SanitizeForLog(origin.KnowledgeBaseID))
+ return info
+ }
+ info.Document = docs[0]
+ return info
+}
+
func (s *agentService) getSelectedDocumentInfos(ctx context.Context, knowledgeIDs []string) ([]*agent.SelectedDocumentInfo, error) {
if len(knowledgeIDs) == 0 {
return []*agent.SelectedDocumentInfo{}, nil
diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go
index 92fe94d74..f41cdcbb1 100644
--- a/internal/application/service/custom_agent.go
+++ b/internal/application/service/custom_agent.go
@@ -724,6 +724,7 @@ func (s *customAgentService) getSuggestedQuestions(
Question: meta.StandardQuestion,
Source: "faq",
KnowledgeBaseID: chunk.KnowledgeBaseID,
+ KnowledgeID: chunk.KnowledgeID,
})
}
}
@@ -757,6 +758,7 @@ func (s *customAgentService) getSuggestedQuestions(
Question: q,
Source: "document",
KnowledgeBaseID: chunk.KnowledgeBaseID,
+ KnowledgeID: chunk.KnowledgeID,
})
}
}
diff --git a/internal/application/service/question_origin_test.go b/internal/application/service/question_origin_test.go
new file mode 100644
index 000000000..8294e57d1
--- /dev/null
+++ b/internal/application/service/question_origin_test.go
@@ -0,0 +1,144 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/agent"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// A client-supplied origin is a hint inside this turn's search targets. It
+// must survive document- and tag-only scopes, whose bases never appear in the
+// resolved KB list, and must never point outside the targets.
+func TestQuestionOriginInTargets(t *testing.T) {
+ ctx := context.Background()
+ origin := func(kbID, docID string) *types.QuestionOrigin {
+ return &types.QuestionOrigin{KnowledgeBaseID: kbID, KnowledgeID: docID}
+ }
+ wholeBase := types.SearchTargets{{Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-a"}}
+ // Selected files, or a document-KB tag scope resolved to its documents.
+ documents := types.SearchTargets{{
+ Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-a", KnowledgeIDs: []string{"doc-1", "doc-2"},
+ }}
+ // An FAQ tag scope filters chunks inside the base; documents cannot be checked.
+ faqTags := types.SearchTargets{{
+ Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-a", TagIDs: []string{"tag-1"},
+ }}
+
+ for _, tc := range []struct {
+ name string
+ origin *types.QuestionOrigin
+ targets types.SearchTargets
+ want *types.QuestionOrigin
+ }{
+ {"whole base keeps document", origin(" kb-a ", " doc-9 "), wholeBase, origin("kb-a", "doc-9")},
+ {"document scope keeps listed document", origin("kb-a", "doc-2"), documents, origin("kb-a", "doc-2")},
+ {"document scope drops unlisted document", origin("kb-a", "doc-9"), documents, origin("kb-a", "")},
+ {"tag-filtered base keeps base only", origin("kb-a", "doc-1"), faqTags, origin("kb-a", "")},
+ {"base outside targets", origin("kb-other", "doc-1"), wholeBase, nil},
+ {"no targets", origin("kb-a", ""), nil, nil},
+ {"empty base", origin("", "doc-1"), wholeBase, nil},
+ {"no origin", nil, wholeBase, nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ assert.Equal(t, tc.want, questionOriginInTargets(ctx, tc.origin, tc.targets))
+ })
+ }
+}
+
+// An agent that retrieves only on @mention treats a picked suggestion from
+// one of its bases as selecting that base, and nothing outside its scope.
+func TestResolveKnowledgeBasesAnchorsOnQuestionOriginWhenRetrievingOnlyOnMention(t *testing.T) {
+ svc := &sessionService{}
+ request := func(originKB string) *types.QARequest {
+ req := &types.QARequest{
+ Session: &types.Session{TenantID: 10000},
+ CustomAgent: &types.CustomAgent{TenantID: 10000, Config: types.CustomAgentConfig{
+ KBSelectionMode: "selected",
+ KnowledgeBases: []string{"kb-a", "kb-b"},
+ RetrieveKBOnlyWhenMentioned: true,
+ }},
+ }
+ if originKB != "" {
+ req.QuestionOrigin = &types.QuestionOrigin{KnowledgeBaseID: originKB, KnowledgeID: "doc-1"}
+ }
+ return req
+ }
+
+ kbIDs, knowledgeIDs, err := svc.resolveKnowledgeBases(context.Background(), request("kb-b"))
+ require.NoError(t, err)
+ assert.Equal(t, []string{"kb-b"}, kbIDs)
+ assert.Empty(t, knowledgeIDs)
+
+ kbIDs, _, err = svc.resolveKnowledgeBases(context.Background(), request("kb-outside"))
+ require.NoError(t, err)
+ assert.Empty(t, kbIDs, "an origin outside the agent's bases must not enable retrieval")
+
+ kbIDs, _, err = svc.resolveKnowledgeBases(context.Background(), request(""))
+ require.NoError(t, err)
+ assert.Empty(t, kbIDs)
+}
+
+type questionOriginKBService struct {
+ interfaces.KnowledgeBaseService
+ kbs map[string]*types.KnowledgeBase
+}
+
+func (s *questionOriginKBService) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
+ if kb := s.kbs[id]; kb != nil {
+ return kb, nil
+ }
+ return nil, errors.New("not found")
+}
+
+func TestResolveQuestionOriginInfo(t *testing.T) {
+ svc := &agentService{
+ knowledgeService: &tagTargetKnowledgeService{knowledges: []*types.Knowledge{
+ {ID: "doc-in", KnowledgeBaseID: "kb-a", Title: "Corners"},
+ {ID: "doc-elsewhere", KnowledgeBaseID: "kb-b", Title: "Other"},
+ {ID: "doc-c", KnowledgeBaseID: "kb-c", Title: "File"},
+ }},
+ knowledgeBaseService: &questionOriginKBService{kbs: map[string]*types.KnowledgeBase{
+ "kb-c": {ID: "kb-c", Name: "Files"},
+ }},
+ }
+ targets := types.SearchTargets{
+ {Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-a"},
+ {Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-c", KnowledgeIDs: []string{"doc-c"}},
+ }
+ kbInfos := []*agent.KnowledgeBaseInfo{{ID: "kb-a", Name: "TEST"}}
+ ctx := context.Background()
+ resolve := func(kbID, docID string) *agent.QuestionOriginInfo {
+ return svc.resolveQuestionOriginInfo(ctx, &types.QuestionOrigin{KnowledgeBaseID: kbID, KnowledgeID: docID},
+ targets, kbInfos)
+ }
+
+ info := resolve("kb-a", "doc-in")
+ require.NotNil(t, info)
+ assert.Equal(t, "TEST", info.KnowledgeBaseName)
+ require.NotNil(t, info.Document)
+ assert.Equal(t, "Corners", info.Document.Title)
+
+ info = resolve("kb-a", "doc-elsewhere")
+ require.NotNil(t, info)
+ assert.Nil(t, info.Document, "a document from another base must be dropped")
+
+ info = resolve("kb-a", "missing")
+ require.NotNil(t, info)
+ assert.Nil(t, info.Document)
+
+ // A base reached through a file scope is not in kbInfos when other bases
+ // are selected; its name is looked up instead of rendered empty.
+ info = resolve("kb-c", "doc-c")
+ require.NotNil(t, info)
+ assert.Equal(t, "Files", info.KnowledgeBaseName)
+ require.NotNil(t, info.Document)
+
+ assert.Nil(t, resolve("kb-b", "doc-elsewhere"), "a base outside the search targets must be dropped")
+ assert.Nil(t, svc.resolveQuestionOriginInfo(ctx, nil, targets, kbInfos))
+}
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index 82959bb57..fa989efb5 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -5,6 +5,8 @@ import (
"encoding/json"
"errors"
"fmt"
+ "slices"
+ "strings"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/event"
@@ -12,6 +14,7 @@ import (
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
)
// AgentQA performs agent-based question answering with conversation history and streaming support
@@ -409,6 +412,7 @@ func (s *sessionService) buildAgentConfig(
return nil, fmt.Errorf("build search targets: %w", err)
}
agentConfig.SearchTargets = searchTargets
+ agentConfig.QuestionOrigin = questionOriginInTargets(ctx, req.QuestionOrigin, searchTargets)
// Document tags are stored in knowledge_tag_relations, so document-KB tag
// scopes are resolved to concrete knowledge IDs before retrieval. Preserve
// those resolved IDs as this turn's pinned documents as well: otherwise the
@@ -645,3 +649,52 @@ func (s *sessionService) configureSkillsFromAgent(
logger.Warnf(ctx, "Unknown SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
}
}
+
+// questionOriginInTargets keeps a suggested question's origin only when this
+// turn's search targets reach it, so the hint never points the model at
+// anything the tools cannot read. The base must be searched this turn (a whole
+// base, or a document/tag scope inside it); the document is kept only when a
+// target for that base covers it.
+func questionOriginInTargets(
+ ctx context.Context, origin *types.QuestionOrigin, targets types.SearchTargets,
+) *types.QuestionOrigin {
+ if origin == nil {
+ return nil
+ }
+ kbID := strings.TrimSpace(origin.KnowledgeBaseID)
+ if kbID == "" {
+ return nil
+ }
+ if !targets.ContainsKB(kbID) {
+ logger.Infof(ctx, "Ignoring question origin: knowledge base %s is outside this turn's search targets",
+ secutils.SanitizeForLog(kbID))
+ return nil
+ }
+ kept := &types.QuestionOrigin{KnowledgeBaseID: kbID}
+ if docID := strings.TrimSpace(origin.KnowledgeID); docID != "" && targetsCoverDocument(targets, kbID, docID) {
+ kept.KnowledgeID = docID
+ }
+ return kept
+}
+
+// targetsCoverDocument reports whether a target for kbID can read docID: an
+// unfiltered whole-base target, or a document scope that lists it. A
+// tag-filtered base cannot be checked per document here, so it does not count.
+func targetsCoverDocument(targets types.SearchTargets, kbID, docID string) bool {
+ for _, t := range targets {
+ if t == nil || t.KnowledgeBaseID != kbID {
+ continue
+ }
+ switch t.Type {
+ case types.SearchTargetTypeKnowledgeBase:
+ if len(t.TagIDs) == 0 {
+ return true
+ }
+ case types.SearchTargetTypeKnowledge:
+ if slices.Contains(t.KnowledgeIDs, docID) {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/application/service/session_qa_helpers.go b/internal/application/service/session_qa_helpers.go
index 4b511a744..65eccaff4 100644
--- a/internal/application/service/session_qa_helpers.go
+++ b/internal/application/service/session_qa_helpers.go
@@ -3,10 +3,12 @@ package service
import (
"context"
"fmt"
+ "slices"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
)
// ---------------------------------------------------------------------------
@@ -44,7 +46,16 @@ func (s *sessionService) resolveKnowledgeBases(
} else if customAgent != nil && customAgent.Config.RetrieveKBOnlyWhenMentioned {
kbIDs = nil
knowledgeIDs = nil
- logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned is enabled and no @ mention found, KB retrieval disabled for this request")
+ if anchor := s.questionOriginAnchor(ctx, customAgent, req); anchor != "" {
+ // Picking a suggestion generated from a base the agent may read
+ // selects that base, as an @mention would.
+ kbIDs = []string{anchor}
+ logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned: retrieving from the picked suggestion's knowledge base %s",
+ secutils.SanitizeForLog(anchor))
+ } else {
+ logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned is enabled and no @ mention found, "+
+ "KB retrieval disabled for this request")
+ }
} else if customAgent != nil {
kbIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, req.Session.TenantID)
}
@@ -59,6 +70,23 @@ func (s *sessionService) resolveKnowledgeBases(
return kbIDs, knowledgeIDs, nil
}
+// questionOriginAnchor returns the knowledge base a picked suggested question
+// came from when the agent is allowed to read it, or "" otherwise. It lets a
+// suggestion work for an agent that retrieves only on @mention, without
+// reaching any base outside the agent's configured scope.
+func (s *sessionService) questionOriginAnchor(
+ ctx context.Context, agent *types.CustomAgent, req *types.QARequest,
+) string {
+ if req.QuestionOrigin == nil || req.Session == nil {
+ return ""
+ }
+ kbID := strings.TrimSpace(req.QuestionOrigin.KnowledgeBaseID)
+ if kbID == "" || !slices.Contains(s.resolveKnowledgeBasesFromAgent(ctx, agent, req.Session.TenantID), kbID) {
+ return ""
+ }
+ return kbID
+}
+
func (s *sessionService) restrictTagScopesToAgentScope(
ctx context.Context,
agent *types.CustomAgent,
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index d50476d63..0234d64a5 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -65,6 +65,7 @@ type qaRequestContext struct {
attachmentIDs []string // Pre-uploaded session-scoped document IDs, resolved after SSE starts
attachmentMetas types.MessageAttachments // Metadata-only view of attachmentIDs for the persisted user message
suggestionAttribution *types.SuggestionAttribution
+ questionOrigin *types.QuestionOrigin
// resourceRewriter turns internal storage references in the outbound stream
// into directly loadable URLs when the caller asks for `resource_urls=public`.
// Disabled (a pass-through) in the default handle mode.
@@ -115,6 +116,7 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {
WebSearchEnabled: rc.webSearchEnabled,
LocalBrowserEnabled: rc.localBrowserEnabled,
Attachments: rc.attachments,
+ QuestionOrigin: rc.questionOrigin,
}
if rc.steerSink != nil {
req.SteerSink = rc.steerSink
@@ -420,6 +422,7 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
attachmentIDs: attachmentIDs,
attachmentMetas: attachmentMetas,
suggestionAttribution: request.SuggestionAttribution,
+ questionOrigin: request.QuestionOrigin,
reqAgentEnabled: request.AgentEnabled,
reqAgentID: request.AgentID,
resourceRewriter: resourceRewriter,
diff --git a/internal/handler/session/types.go b/internal/handler/session/types.go
index 4ba92aae8..8059c1b7d 100644
--- a/internal/handler/session/types.go
+++ b/internal/handler/session/types.go
@@ -61,6 +61,8 @@ type CreateKnowledgeQARequest struct {
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
+ // QuestionOrigin is the knowledge source of a picked suggested question.
+ QuestionOrigin *types.QuestionOrigin `json:"question_origin,omitempty"`
}
// AttachmentUpload represents a file attachment upload from the client
diff --git a/internal/types/agent.go b/internal/types/agent.go
index 85462fe14..9558d5fe6 100644
--- a/internal/types/agent.go
+++ b/internal/types/agent.go
@@ -157,6 +157,10 @@ type AgentConfig struct {
// Per-request @mention pins (runtime only; injected as <must_use> in the user message).
PinnedMCPServiceIDs []string `json:"-"`
PinnedSkillNames []string `json:"-"`
+ // QuestionOrigin is the knowledge source of a suggested question the user
+ // picked, already checked to be inside KnowledgeBases (runtime only;
+ // rendered into runtime_context as a retrieval hint).
+ QuestionOrigin *QuestionOrigin `json:"-"`
// SharedAgentReadOnly prevents a shared agent from mutating resources in
// its source workspace. It is set from the verified share relation, never
// inferred from a client-provided tenant ID.
diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go
index 53dd2906d..3002ae1ce 100644
--- a/internal/types/custom_agent.go
+++ b/internal/types/custom_agent.go
@@ -587,6 +587,8 @@ type SuggestedQuestion struct {
Source string `json:"source"`
// 来源知识库ID(仅 faq/document/wiki 来源时有值)
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
+ // 来源文档ID(仅 faq/document 来源时有值)
+ KnowledgeID string `json:"knowledge_id,omitempty"`
}
// BuiltinAgentRegistry provides a registry of all built-in agents.
diff --git a/internal/types/qa_request.go b/internal/types/qa_request.go
index 6bb348120..e626dab91 100644
--- a/internal/types/qa_request.go
+++ b/internal/types/qa_request.go
@@ -39,6 +39,15 @@ type SteerSink interface {
) string
}
+// QuestionOrigin names the knowledge source a suggested question was
+// generated from. The client sends it with the question the user picked so
+// the agent searches that source before answering; it is a hint inside the
+// turn's resolved scope, never a scope change.
+type QuestionOrigin struct {
+ KnowledgeBaseID string `json:"knowledge_base_id"`
+ KnowledgeID string `json:"knowledge_id,omitempty"`
+}
+
// QARequest consolidates all parameters for KnowledgeQA and AgentQA service calls,
// replacing the previous 14-parameter method signatures.
// EventBus is passed separately to avoid circular dependency with the event package.
@@ -61,6 +70,7 @@ type QARequest struct {
WebSearchEnabled bool // Whether web search is enabled for this request
QuotedContext string // Quoted message content from IM quote-reply (appended at LLM prompt stage, not used for retrieval)
Attachments MessageAttachments // File attachments (processed and ready for prompt injection)
+ QuestionOrigin *QuestionOrigin // Source of a picked suggested question; a retrieval hint only
// SteerSink, when set, enables mid-run message injection for this run:
// the engine drains user-appended messages at every round boundary and
// persists accepted ones through this sink. A structural interface so