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

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

A user picked the suggested question "为什么在比较图形时需要谨慎处理?"
and the agent answered in round 1 with no tool call, claiming it had
searched the knowledge base and found nothing, then explained misleading
statistical charts. The question had been generated from "Corners Don't
Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base,
where "comparing graphs" means SSAO falloff curves.

Two things let that happen: the grounding prompt said "Stable general
explanations need no lookup", and nothing told the agent where the
question came from - the base in question had no profile, only two
recent titles in the directory, and the click sent the text alone.

Prompt
- With knowledge tools available, search bound bases before answering a
  question about a topic, even one that reads like general knowledge;
  directory profiles and recent titles cannot prove a base lacks it.
- The general-explanation exemption applies only without bound bases.
- Say you searched or found nothing only when a search tool ran.

Question origin
- Suggested questions from FAQ/document chunks also return knowledge_id.
- Picking one on the home or chat page sends question_origin
  {knowledge_base_id, knowledge_id} with that question only.
- The service keeps the origin only when its base is inside the turn's
  resolved scope and the document belongs to that base; it never
  changes the scope (unlike knowledge_base_ids, which narrows it).
- The engine renders it in runtime_context as <question_origin> with the
  base and document handles and a note to search it before answering.

* fix(agent): keep question origins across file/tag scopes and bind them to the send

Review follow-up for the suggested-question origin.

- Scope check: the origin was kept only when its base was in the resolved
  KB list, which is empty for file-only and tag-only scopes even though
  their bases are searched. It is now checked against SearchTargets after
  they are built; the document is kept only when a target for that base
  covers it (unfiltered base, or a document scope listing it).
  resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of
  a base that is not in kbInfos, and the renderer omits an unknown name.
- Frontend: the origin travelled through module-level "pending" state, so
  a send that returned early (agent not ready, upload in progress,
  steering) left it behind and a second pick overwrote it. It now rides
  with the one send: triggerSend(text, options) -> createSession ->
  send-msg -> sendMsg / changeFirstQuery.
- RetrieveKBOnlyWhenMentioned: suggestions are still generated from the
  agent's bases, but picking one retrieved nothing. The origin now
  selects its base, as an @mention would, when the agent may read it.
- API sync: question_origin in docs/api/chat.md and swagger;
  QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and
  knowledge_id on SuggestedQuestion.
main
lyingbug 2026-09-18 17:00:47 +08:00 committed by GitHub
parent 9d508c1c7a
commit 2be7bd4063
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
33 changed files with 611 additions and 51 deletions

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 会先检索这个来源再作答;它只是本轮检索范围内的提示,不会扩大范围。对仅在 @ 提及时检索知识库的智能体,若该知识库在智能体可用范围内,则本轮检索该知识库 |
## 回答后推荐问题

View File

@ -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",

View File

@ -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",

View File

@ -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:

View File

@ -369,6 +369,7 @@ export interface SuggestedQuestion {
question: string;
source: 'faq' | 'document' | 'agent_config' | 'wiki';
knowledge_base_id?: string;
knowledge_id?: string;
}
// 获取智能体推荐问题

View File

@ -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 = {

View File

@ -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

View File

@ -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,

View File

@ -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)
})

View File

@ -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
}

View File

@ -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/)
})

View File

@ -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;

View File

@ -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}`);
}

View File

@ -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

View File

@ -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 " +

View File

@ -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"},
},
{

View File

@ -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 {

View File

@ -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{{

View File

@ -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>")
}

View File

@ -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.

View File

@ -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

View File

@ -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,
})
}
}

View File

@ -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))
}

View File

@ -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
}

View File

@ -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,

View File

@ -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,

View File

@ -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

View File

@ -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.

View File

@ -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.

View File

@ -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