feat(chat): add @Skill/@MCP mentions with scoped agent runtime
Wire per-turn @mentions for skills, MCP services, tags, and files through QA handlers into agent config, runtime_context/must_use user blocks, and tool registration. Fix tag-only scopes dropping KB tools, refresh suggested questions on mention changes, and strengthen MCP must_use so @selected services are invoked before local KB search.
This commit is contained in:
+29
-28
@@ -38,6 +38,8 @@ type AgentEngine struct {
|
||||
eventBus *event.EventBus
|
||||
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
|
||||
selectedDocs []*SelectedDocumentInfo // User-selected documents (via @ mention)
|
||||
pinnedMCPServices []*PinnedMCPServiceInfo // User @mentioned MCP services for this turn
|
||||
pinnedSkills []*PinnedSkillInfo // User @mentioned skills for this turn
|
||||
sessionID string // Session ID for logging and event emission
|
||||
systemPromptTemplate string // System prompt template (optional, uses default if empty)
|
||||
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
|
||||
@@ -93,6 +95,32 @@ func NewAgentEngine(
|
||||
return engine
|
||||
}
|
||||
|
||||
// SetPinnedMentions sets per-turn @mention scope for MCP services and skills.
|
||||
func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) {
|
||||
e.pinnedMCPServices = mcpServices
|
||||
e.pinnedSkills = skills
|
||||
}
|
||||
|
||||
func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromptOptions {
|
||||
opts := &BuildSystemPromptOptions{
|
||||
Language: types.LanguageNameFromContext(ctx),
|
||||
Config: e.appConfig,
|
||||
}
|
||||
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
|
||||
opts.SkillsMetadata = e.skillsManager.GetAllMetadata()
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func (e *AgentEngine) buildSystemPrompt(ctx context.Context) string {
|
||||
return BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.systemPromptOptions(ctx),
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
}
|
||||
|
||||
// NewAgentEngineWithSkills creates a new agent engine with skills support
|
||||
func NewAgentEngineWithSkills(
|
||||
config *types.AgentConfig,
|
||||
@@ -220,34 +248,7 @@ func (e *AgentEngine) Execute(
|
||||
|
||||
// Build system prompt using progressive RAG prompt
|
||||
// If skills are enabled, include skills metadata (Level 1 - Progressive Disclosure)
|
||||
// Extract user language from context for prompt placeholder
|
||||
language := types.LanguageNameFromContext(ctx)
|
||||
var systemPrompt string
|
||||
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
|
||||
skillsMetadata := e.skillsManager.GetAllMetadata()
|
||||
systemPrompt = BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
SkillsMetadata: skillsMetadata,
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
} else {
|
||||
systemPrompt = BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
}
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
logger.Debugf(ctx, "[Agent] SystemPrompt: %d chars", len(systemPrompt))
|
||||
|
||||
// Initialize messages with history
|
||||
|
||||
@@ -31,17 +31,7 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
||||
})
|
||||
|
||||
// Build messages with all context
|
||||
language := types.LanguageNameFromContext(ctx)
|
||||
systemPrompt := BuildSystemPromptWithOptions(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.selectedDocs,
|
||||
&BuildSystemPromptOptions{
|
||||
Language: language,
|
||||
Config: e.appConfig,
|
||||
},
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
systemPrompt := e.buildSystemPrompt(ctx)
|
||||
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
|
||||
@@ -217,7 +217,8 @@ func escapeXMLAttr(s string) string {
|
||||
// to the user query rather than baked into the system prompt. Keeping it in
|
||||
// the user message keeps the system prompt stable/cacheable and lets the
|
||||
// model see exactly which KBs were in scope at the time of each historical
|
||||
// turn.
|
||||
// turn. Per-turn @mentioned MCP/Skill requirements are emitted separately via
|
||||
// buildMustUseBlock (sibling to runtime_context in the user message).
|
||||
//
|
||||
// Per-turn communication_instruction and answer_instruction remind the model
|
||||
// not to leak internal tool names or IDs in user-visible text, and to end the
|
||||
@@ -232,7 +233,7 @@ func buildRuntimeContextBlock(
|
||||
docs []*SelectedDocumentInfo,
|
||||
) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<runtime_context note=\"turn metadata; follow communication_instruction and answer_instruction\">\n")
|
||||
sb.WriteString("<runtime_context scope=\"this_turn\">\n")
|
||||
fmt.Fprintf(&sb, " <current_time>%s</current_time>\n", time.Now().Format(time.RFC3339))
|
||||
fmt.Fprintf(&sb, " <session>%s</session>\n", escapeXMLAttr(sessionID))
|
||||
|
||||
@@ -261,11 +262,18 @@ func buildRuntimeContextBlock(
|
||||
if title == "" {
|
||||
title = d.KnowledgeID
|
||||
}
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title))
|
||||
if d.FileType != "" {
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" file_type=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title), escapeXMLAttr(d.FileType))
|
||||
} else {
|
||||
fmt.Fprintf(&sb, " <document knowledge_id=\"%s\" title=\"%s\" />\n",
|
||||
escapeXMLAttr(d.KnowledgeID), escapeXMLAttr(title))
|
||||
}
|
||||
}
|
||||
sb.WriteString(" </pinned_documents>\n")
|
||||
sb.WriteString(" <note>The pinned-document set above is authoritative for THIS turn. If an earlier turn in this conversation analysed a different document, do NOT reuse that analysis — re-query against the current scope.</note>\n")
|
||||
sb.WriteString(" <note>The pinned-document set above is authoritative for THIS turn. ")
|
||||
sb.WriteString("Prioritize retrieving content from these documents (e.g. list_knowledge_chunks with the knowledge_id). ")
|
||||
sb.WriteString("If an earlier turn analysed a different document, do NOT reuse that analysis — re-query against the current scope.</note>\n")
|
||||
}
|
||||
|
||||
sb.WriteString(" <communication_instruction>Do not use internal tool names or identifiers in your answers or in Thought. Say \"keyword retrieval\" instead of grep_chunks, \"semantic retrieval\" instead of knowledge_search, \"browse full document\" instead of list_knowledge_chunks; likewise never expose chunk_id, knowledge_id, or other internal IDs—refer to documents by title or name.</communication_instruction>\n")
|
||||
@@ -275,6 +283,54 @@ func buildRuntimeContextBlock(
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// buildMustUseBlock emits per-turn @mentioned MCP/Skill requirements as a
|
||||
// sibling envelope outside runtime_context.
|
||||
func buildMustUseBlock(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo) string {
|
||||
if len(mcpServices) == 0 && len(skills) == 0 {
|
||||
return ""
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<must_use>\n")
|
||||
sb.WriteString(" <instruction>REQUIRED this turn: the user @selected these capabilities. ")
|
||||
sb.WriteString("For EACH listed MCP service you MUST call at least one tool from its tools= list ")
|
||||
sb.WriteString("in your FIRST tool round (before grep_chunks / knowledge_search / wiki_search). ")
|
||||
sb.WriteString("For EACH listed skill call read_skill(skill_name=...) before your final answer. ")
|
||||
sb.WriteString("The @mention means the user wants that source — do not answer using only local KB retrieval when an MCP service is listed.</instruction>\n")
|
||||
for _, svc := range mcpServices {
|
||||
if svc == nil {
|
||||
continue
|
||||
}
|
||||
name := svc.Name
|
||||
if name == "" {
|
||||
name = svc.ID
|
||||
}
|
||||
if len(svc.ToolNames) > 0 {
|
||||
fmt.Fprintf(&sb, " <mcp name=\"%s\" tools=\"%s\" />\n",
|
||||
escapeXMLAttr(name), escapeXMLAttr(strings.Join(svc.ToolNames, ", ")))
|
||||
} else {
|
||||
fmt.Fprintf(&sb, " <mcp name=\"%s\" />\n", escapeXMLAttr(name))
|
||||
}
|
||||
}
|
||||
for _, skill := range skills {
|
||||
if skill == nil || skill.Name == "" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&sb, " <skill name=\"%s\" />\n", escapeXMLAttr(skill.Name))
|
||||
}
|
||||
sb.WriteString("</must_use>")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func composeUserTurnContent(parts ...string) string {
|
||||
nonEmpty := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if strings.TrimSpace(part) != "" {
|
||||
nonEmpty = append(nonEmpty, part)
|
||||
}
|
||||
}
|
||||
return strings.Join(nonEmpty, "\n\n")
|
||||
}
|
||||
|
||||
// listToolNames returns tool.function names for logging
|
||||
func listToolNames(ts []chat.Tool) []string {
|
||||
names := make([]string, 0, len(ts))
|
||||
@@ -441,9 +497,10 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
|
||||
// this is what lets the model detect a scope switch instead of silently
|
||||
// answering the new question against last turn's retrieval.
|
||||
runtimeCtx := buildRuntimeContextBlock(sessionID, e.knowledgeBasesInfo, e.selectedDocs)
|
||||
mustUse := buildMustUseBlock(e.pinnedMCPServices, e.pinnedSkills)
|
||||
userMsg := chat.Message{
|
||||
Role: "user",
|
||||
Content: runtimeCtx + "\n\n" + currentQuery,
|
||||
Content: composeUserTurnContent(runtimeCtx, mustUse, currentQuery),
|
||||
Images: imageURLs,
|
||||
}
|
||||
messages = append(messages, userMsg)
|
||||
|
||||
@@ -147,3 +147,54 @@ func TestAppendToolResults_PreservesReasoningContent(t *testing.T) {
|
||||
assert.Equal(t, "thinking", out[2].ReasoningContent)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildRuntimeContextBlock_PinnedDocuments(t *testing.T) {
|
||||
block := buildRuntimeContextBlock(
|
||||
"sess-1",
|
||||
nil,
|
||||
[]*SelectedDocumentInfo{{
|
||||
KnowledgeID: "kid-1",
|
||||
Title: "Report.pdf",
|
||||
FileType: "pdf",
|
||||
}},
|
||||
)
|
||||
|
||||
assert.Contains(t, block, "<pinned_documents")
|
||||
assert.Contains(t, block, `knowledge_id="kid-1"`)
|
||||
assert.Contains(t, block, `title="Report.pdf"`)
|
||||
assert.Contains(t, block, `file_type="pdf"`)
|
||||
assert.Contains(t, block, "list_knowledge_chunks")
|
||||
assert.NotContains(t, block, "<must_use>")
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MCPAndSkills(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "ChemDB",
|
||||
}},
|
||||
[]*PinnedSkillInfo{{
|
||||
Name: "data-analysis",
|
||||
}},
|
||||
)
|
||||
|
||||
assert.Contains(t, block, "<must_use>")
|
||||
assert.NotContains(t, block, "<runtime_context")
|
||||
assert.Contains(t, block, "<instruction>REQUIRED this turn")
|
||||
assert.Contains(t, block, "FIRST tool round")
|
||||
assert.Contains(t, block, "read_skill")
|
||||
assert.Contains(t, block, `<mcp name="ChemDB"`)
|
||||
assert.Contains(t, block, `<skill name="data-analysis"`)
|
||||
}
|
||||
|
||||
func TestBuildMustUseBlock_MCPToolNames(t *testing.T) {
|
||||
block := buildMustUseBlock(
|
||||
[]*PinnedMCPServiceInfo{{
|
||||
ID: "mcp-1",
|
||||
Name: "iwiki",
|
||||
ToolNames: []string{"mcp_iwiki_aisearchdocument", "mcp_iwiki_getdocument"},
|
||||
}},
|
||||
nil,
|
||||
)
|
||||
assert.Contains(t, block, `tools="mcp_iwiki_aisearchdocument, mcp_iwiki_getdocument"`)
|
||||
}
|
||||
|
||||
+21
-43
@@ -61,8 +61,8 @@ type RecentDocInfo struct {
|
||||
FAQAnswers []string
|
||||
}
|
||||
|
||||
// SelectedDocumentInfo contains summary information about a user-selected document (via @ mention)
|
||||
// Only metadata is included; content will be fetched via tools when needed
|
||||
// SelectedDocumentInfo contains summary information about a user-selected document (via @ mention).
|
||||
// Injected into the user message runtime_context (pinned_documents); content is fetched via tools.
|
||||
type SelectedDocumentInfo struct {
|
||||
KnowledgeID string // Knowledge ID
|
||||
KnowledgeBaseID string // Knowledge base ID
|
||||
@@ -71,6 +71,20 @@ type SelectedDocumentInfo struct {
|
||||
FileType string // File type (pdf, docx, etc.)
|
||||
}
|
||||
|
||||
// PinnedMCPServiceInfo describes an MCP service explicitly @mentioned for this turn.
|
||||
type PinnedMCPServiceInfo struct {
|
||||
ID string
|
||||
Name string
|
||||
Description string
|
||||
ToolNames []string // Registered tool.function names for this service (mcp_{service}_{tool})
|
||||
}
|
||||
|
||||
// PinnedSkillInfo describes a preloaded skill explicitly @mentioned for this turn.
|
||||
type PinnedSkillInfo struct {
|
||||
Name string
|
||||
Description string
|
||||
}
|
||||
|
||||
// KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
|
||||
type KnowledgeBaseInfo struct {
|
||||
ID string
|
||||
@@ -159,7 +173,7 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
} else {
|
||||
b.WriteString("<recent_documents>\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 {
|
||||
if j >= 2 {
|
||||
break
|
||||
}
|
||||
docName := doc.Title
|
||||
@@ -194,6 +208,9 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
// placeholder is expanded to a short pointer so legacy / custom
|
||||
// templates that still reference `{{knowledge_bases}}` degrade
|
||||
// gracefully instead of dumping the detail twice.
|
||||
// - `<must_use>` is NOT a placeholder — when the user @mentions MCP/Skill,
|
||||
// observe.buildMustUseBlock injects it as a sibling block in the user
|
||||
// message; system prompts document it by convention (see agent_system_prompt.yaml).
|
||||
func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseInfo) string {
|
||||
result := template
|
||||
|
||||
@@ -245,38 +262,6 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// formatSelectedDocuments formats selected documents for the prompt (summary only, no content)
|
||||
func formatSelectedDocuments(docs []*SelectedDocumentInfo) string {
|
||||
if len(docs) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
builder.WriteString("\n### User Selected Documents (via @ mention)\n")
|
||||
builder.WriteString("The user has explicitly selected the following documents. ")
|
||||
builder.WriteString("**You should prioritize searching and retrieving information from these documents when answering.**\n")
|
||||
builder.WriteString("Use `list_knowledge_chunks` with the provided Knowledge IDs to fetch their content.\n\n")
|
||||
|
||||
builder.WriteString("| # | Document Name | Type | Knowledge ID |\n")
|
||||
builder.WriteString("|---|---------------|------|---------------|\n")
|
||||
|
||||
for i, doc := range docs {
|
||||
title := doc.Title
|
||||
if title == "" {
|
||||
title = doc.FileName
|
||||
}
|
||||
fileType := doc.FileType
|
||||
if fileType == "" {
|
||||
fileType = "-"
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf("| %d | %s | %s | `%s` |\n",
|
||||
i+1, title, fileType, doc.KnowledgeID))
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// renderPromptPlaceholdersWithStatus renders placeholders including web search status
|
||||
// Supported placeholders:
|
||||
// - {{knowledge_bases}}
|
||||
@@ -320,17 +305,15 @@ type BuildSystemPromptOptions struct {
|
||||
func BuildSystemPrompt(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
selectedDocs []*SelectedDocumentInfo,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
return BuildSystemPromptWithOptions(knowledgeBases, webSearchEnabled, selectedDocs, nil, systemPromptTemplate...)
|
||||
return BuildSystemPromptWithOptions(knowledgeBases, webSearchEnabled, nil, systemPromptTemplate...)
|
||||
}
|
||||
|
||||
// BuildSystemPromptWithOptions builds the system prompt with additional options like skills
|
||||
func BuildSystemPromptWithOptions(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
selectedDocs []*SelectedDocumentInfo,
|
||||
options *BuildSystemPromptOptions,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
@@ -361,11 +344,6 @@ func BuildSystemPromptWithOptions(
|
||||
}
|
||||
basePrompt = renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime, language)
|
||||
|
||||
// Append selected documents section if any
|
||||
if len(selectedDocs) > 0 {
|
||||
basePrompt += formatSelectedDocuments(selectedDocs)
|
||||
}
|
||||
|
||||
// Append skills metadata if available (Level 1 - Progressive Disclosure)
|
||||
if options != nil && len(options.SkillsMetadata) > 0 {
|
||||
basePrompt += formatSkillsMetadata(options.SkillsMetadata)
|
||||
|
||||
@@ -512,7 +512,7 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
var fullKBIDs []string
|
||||
var knowledgeTargets []*types.SearchTarget
|
||||
for _, st := range targets {
|
||||
if st.Type == types.SearchTargetTypeKnowledgeBase {
|
||||
if st.Type == types.SearchTargetTypeKnowledgeBase && len(st.TagIDs) == 0 {
|
||||
fullKBIDs = append(fullKBIDs, st.KnowledgeBaseID)
|
||||
} else {
|
||||
knowledgeTargets = append(knowledgeTargets, st)
|
||||
@@ -566,6 +566,7 @@ func (t *KnowledgeSearchTool) concurrentSearchByTargets(
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
KnowledgeIDs: st.KnowledgeIDs,
|
||||
TagIDs: st.TagIDs,
|
||||
}
|
||||
kbResults, err := t.knowledgeBaseService.HybridSearch(ctx, st.KnowledgeBaseID, searchParams)
|
||||
if err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -520,6 +521,30 @@ func RegisterMCPTools(
|
||||
return nil
|
||||
}
|
||||
|
||||
// MCPToolNamesByServiceID returns registered MCP tool names grouped by service ID.
|
||||
func MCPToolNamesByServiceID(registry *ToolRegistry) map[string][]string {
|
||||
if registry == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string][]string)
|
||||
for _, name := range registry.ListTools() {
|
||||
tool, err := registry.GetTool(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
mcpTool, ok := tool.(*MCPTool)
|
||||
if !ok || mcpTool.service == nil {
|
||||
continue
|
||||
}
|
||||
sid := mcpTool.service.ID
|
||||
out[sid] = append(out[sid], name)
|
||||
}
|
||||
for sid := range out {
|
||||
sort.Strings(out[sid])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GetMCPToolsInfo returns information about available MCP tools
|
||||
func GetMCPToolsInfo(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -624,9 +624,9 @@ func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
keyword string,
|
||||
offset, limit int,
|
||||
fileTypes []string,
|
||||
) ([]*types.Knowledge, bool, error) {
|
||||
) ([]*types.Knowledge, bool, int64, error) {
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
return nil, false, 0, nil
|
||||
}
|
||||
|
||||
type KnowledgeWithKBName struct {
|
||||
@@ -709,13 +709,18 @@ func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
}
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Session(&gorm.Session{}).Count(&total).Error; err != nil {
|
||||
return nil, false, 0, err
|
||||
}
|
||||
|
||||
var results []KnowledgeWithKBName
|
||||
err := query.Order("knowledges.created_at DESC").
|
||||
Offset(offset).
|
||||
Limit(limit + 1).
|
||||
Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, false, 0, err
|
||||
}
|
||||
|
||||
hasMore := len(results) > limit
|
||||
@@ -729,7 +734,7 @@ func (r *knowledgeRepository) SearchKnowledgeInScopes(
|
||||
k.KnowledgeBaseName = r.KnowledgeBaseName
|
||||
knowledges[i] = &k
|
||||
}
|
||||
return knowledges, hasMore, nil
|
||||
return knowledges, hasMore, total, nil
|
||||
}
|
||||
|
||||
// ListIDsByTagIDs returns all knowledge IDs that have any of the specified tag IDs (OR semantics)
|
||||
|
||||
@@ -43,6 +43,46 @@ func dedupStrings(in []string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// agentHasKnowledgeScope reports whether the agent has any KB retrieval scope for
|
||||
// this turn. Tag-only @mentions populate SearchTargets (with TagIDs) but leave
|
||||
// KnowledgeBases / KnowledgeIDs empty — those must still count as in-scope.
|
||||
func agentHasKnowledgeScope(config *types.AgentConfig) bool {
|
||||
if config == nil {
|
||||
return false
|
||||
}
|
||||
if len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0 {
|
||||
return true
|
||||
}
|
||||
return len(config.SearchTargets) > 0
|
||||
}
|
||||
|
||||
// knowledgeBaseIDsForPrompt returns KB IDs to show in runtime_context metadata.
|
||||
// Prefer explicit KnowledgeBases; fall back to deduped IDs from SearchTargets.
|
||||
func knowledgeBaseIDsForPrompt(config *types.AgentConfig) []string {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
if len(config.KnowledgeBases) > 0 {
|
||||
return config.KnowledgeBases
|
||||
}
|
||||
if len(config.SearchTargets) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{}, len(config.SearchTargets))
|
||||
out := make([]string, 0, len(config.SearchTargets))
|
||||
for _, target := range config.SearchTargets {
|
||||
if target == nil || target.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[target.KnowledgeBaseID]; ok {
|
||||
continue
|
||||
}
|
||||
seen[target.KnowledgeBaseID] = struct{}{}
|
||||
out = append(out, target.KnowledgeBaseID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// agentService implements agent-related business logic
|
||||
type agentService struct {
|
||||
cfg *config.Config
|
||||
@@ -149,6 +189,12 @@ func (s *agentService) CreateAgentEngine(
|
||||
systemPromptTemplate,
|
||||
)
|
||||
engine.SetAppConfig(s.cfg)
|
||||
pinnedMCP := s.resolvePinnedMCPServiceInfos(ctx, config)
|
||||
s.attachPinnedMCPToolNames(toolRegistry, pinnedMCP)
|
||||
engine.SetPinnedMentions(
|
||||
pinnedMCP,
|
||||
s.resolvePinnedSkillInfos(config),
|
||||
)
|
||||
|
||||
// Set VLM image describer for MCP tool result image analysis.
|
||||
// When an MCP tool returns images, the engine uses VLM to generate text descriptions
|
||||
@@ -206,7 +252,11 @@ func (s *agentService) registerMCPTools(
|
||||
var mcpServices []*types.MCPService
|
||||
var err error
|
||||
|
||||
if mcpMode == "selected" && len(config.MCPServices) > 0 {
|
||||
if mcpMode == "selected" {
|
||||
if len(config.MCPServices) == 0 {
|
||||
logger.Infof(ctx, "MCP services disabled by agent config (mode: selected, no services)")
|
||||
return
|
||||
}
|
||||
mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)
|
||||
@@ -241,11 +291,12 @@ func (s *agentService) resolveKBAndDocInfos(
|
||||
ctx context.Context,
|
||||
config *types.AgentConfig,
|
||||
) ([]*agent.KnowledgeBaseInfo, []*agent.SelectedDocumentInfo) {
|
||||
kbInfos, err := s.getKnowledgeBaseInfos(ctx, config.KnowledgeBases)
|
||||
kbIDs := knowledgeBaseIDsForPrompt(config)
|
||||
kbInfos, err := s.getKnowledgeBaseInfos(ctx, kbIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge base details, using IDs only: %v", err)
|
||||
kbInfos = make([]*agent.KnowledgeBaseInfo, 0, len(config.KnowledgeBases))
|
||||
for _, kbID := range config.KnowledgeBases {
|
||||
kbInfos = make([]*agent.KnowledgeBaseInfo, 0, len(kbIDs))
|
||||
for _, kbID := range kbIDs {
|
||||
kbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{
|
||||
ID: kbID,
|
||||
Name: kbID,
|
||||
@@ -393,8 +444,8 @@ func (s *agentService) registerTools(
|
||||
}
|
||||
}
|
||||
|
||||
// Filter out knowledge base tools if no knowledge bases or knowledge IDs are configured
|
||||
hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0
|
||||
// Filter out knowledge base tools if no knowledge scope is configured for this turn.
|
||||
hasKnowledge := agentHasKnowledgeScope(config)
|
||||
if !hasKnowledge {
|
||||
filteredTools := make([]string, 0)
|
||||
kbTools := map[string]bool{
|
||||
@@ -799,3 +850,104 @@ func (s *agentService) getSelectedDocumentInfos(ctx context.Context, knowledgeID
|
||||
logger.Infof(ctx, "Loaded %d selected documents metadata for prompt", len(selectedDocs))
|
||||
return selectedDocs, nil
|
||||
}
|
||||
|
||||
func (s *agentService) resolvePinnedMCPServiceInfos(
|
||||
ctx context.Context,
|
||||
config *types.AgentConfig,
|
||||
) []*agent.PinnedMCPServiceInfo {
|
||||
if len(config.PinnedMCPServiceIDs) == 0 || s.mcpServiceService == nil {
|
||||
return nil
|
||||
}
|
||||
tenantID := uint64(0)
|
||||
if tid, ok := types.TenantIDFromContext(ctx); ok {
|
||||
tenantID = tid
|
||||
}
|
||||
if tenantID == 0 {
|
||||
return fallbackPinnedMCPInfos(config.PinnedMCPServiceIDs)
|
||||
}
|
||||
|
||||
services, err := s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.PinnedMCPServiceIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to resolve pinned MCP services: %v", err)
|
||||
return fallbackPinnedMCPInfos(config.PinnedMCPServiceIDs)
|
||||
}
|
||||
byID := make(map[string]*types.MCPService, len(services))
|
||||
for _, svc := range services {
|
||||
if svc != nil {
|
||||
byID[svc.ID] = svc
|
||||
}
|
||||
}
|
||||
result := make([]*agent.PinnedMCPServiceInfo, 0, len(config.PinnedMCPServiceIDs))
|
||||
for _, id := range config.PinnedMCPServiceIDs {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if svc, ok := byID[id]; ok {
|
||||
result = append(result, &agent.PinnedMCPServiceInfo{
|
||||
ID: svc.ID,
|
||||
Name: svc.Name,
|
||||
Description: svc.Description,
|
||||
})
|
||||
continue
|
||||
}
|
||||
result = append(result, &agent.PinnedMCPServiceInfo{ID: id, Name: id})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *agentService) attachPinnedMCPToolNames(
|
||||
registry *tools.ToolRegistry,
|
||||
pinned []*agent.PinnedMCPServiceInfo,
|
||||
) {
|
||||
if registry == nil || len(pinned) == 0 {
|
||||
return
|
||||
}
|
||||
byService := tools.MCPToolNamesByServiceID(registry)
|
||||
for _, info := range pinned {
|
||||
if info == nil || info.ID == "" {
|
||||
continue
|
||||
}
|
||||
info.ToolNames = append([]string(nil), byService[info.ID]...)
|
||||
}
|
||||
}
|
||||
|
||||
func fallbackPinnedMCPInfos(ids []string) []*agent.PinnedMCPServiceInfo {
|
||||
result := make([]*agent.PinnedMCPServiceInfo, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, &agent.PinnedMCPServiceInfo{ID: id, Name: id})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *agentService) resolvePinnedSkillInfos(config *types.AgentConfig) []*agent.PinnedSkillInfo {
|
||||
if len(config.PinnedSkillNames) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
descByName := make(map[string]string)
|
||||
if len(config.SkillDirs) > 0 {
|
||||
loader := skills.NewLoader(config.SkillDirs)
|
||||
if metadata, err := loader.DiscoverSkills(); err == nil {
|
||||
for _, meta := range metadata {
|
||||
if meta != nil {
|
||||
descByName[meta.Name] = meta.Description
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]*agent.PinnedSkillInfo, 0, len(config.PinnedSkillNames))
|
||||
for _, name := range config.PinnedSkillNames {
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, &agent.PinnedSkillInfo{
|
||||
Name: name,
|
||||
Description: descByName[name],
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAgentHasKnowledgeScope_TagOnlySearchTargets(t *testing.T) {
|
||||
cfg := &types.AgentConfig{
|
||||
SearchTargets: types.SearchTargets{
|
||||
{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: "kb-1",
|
||||
TagIDs: []string{"tag-a"},
|
||||
},
|
||||
},
|
||||
}
|
||||
assert.True(t, agentHasKnowledgeScope(cfg))
|
||||
}
|
||||
|
||||
func TestAgentHasKnowledgeScope_Empty(t *testing.T) {
|
||||
assert.False(t, agentHasKnowledgeScope(&types.AgentConfig{}))
|
||||
assert.False(t, agentHasKnowledgeScope(nil))
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseIDsForPrompt_FromSearchTargets(t *testing.T) {
|
||||
cfg := &types.AgentConfig{
|
||||
SearchTargets: types.SearchTargets{
|
||||
{KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-a"}},
|
||||
{KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-b"}},
|
||||
{KnowledgeBaseID: "kb-2", TagIDs: []string{"tag-c"}},
|
||||
},
|
||||
}
|
||||
assert.Equal(t, []string{"kb-1", "kb-2"}, knowledgeBaseIDsForPrompt(cfg))
|
||||
}
|
||||
@@ -57,6 +57,7 @@ func (p *PluginSearch) runQueryExpansion(ctx context.Context, chatManage *types.
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: expKwTh,
|
||||
MatchCount: expTopK,
|
||||
TagIDs: t.TagIDs,
|
||||
DisableVectorMatch: false,
|
||||
DisableKeywordsMatch: false,
|
||||
SkipContextEnrichment: true, // Pipeline handles context assembly in merge stage
|
||||
|
||||
@@ -386,7 +386,7 @@ func (p *PluginSearch) searchByTargets(
|
||||
var fullKBIDs []string
|
||||
var knowledgeTargets []*types.SearchTarget
|
||||
for _, t := range targets {
|
||||
if t.Type == types.SearchTargetTypeKnowledgeBase {
|
||||
if t.Type == types.SearchTargetTypeKnowledgeBase && len(t.TagIDs) == 0 {
|
||||
fullKBIDs = append(fullKBIDs, t.KnowledgeBaseID)
|
||||
} else {
|
||||
knowledgeTargets = append(knowledgeTargets, t)
|
||||
@@ -502,6 +502,7 @@ func (p *PluginSearch) searchSingleTarget(
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
TagIDs: t.TagIDs,
|
||||
SkipContextEnrichment: true,
|
||||
}
|
||||
if t.Type == types.SearchTargetTypeKnowledge {
|
||||
|
||||
@@ -30,6 +30,8 @@ type customAgentService struct {
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
kbShareService interfaces.KBShareService
|
||||
wikiPageRepo interfaces.WikiPageRepository
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
knowledgeRepo interfaces.KnowledgeRepository
|
||||
}
|
||||
|
||||
// NewCustomAgentService creates a new custom agent service
|
||||
@@ -39,6 +41,8 @@ func NewCustomAgentService(
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
kbShareService interfaces.KBShareService,
|
||||
wikiPageRepo interfaces.WikiPageRepository,
|
||||
tagRepo interfaces.KnowledgeTagRepository,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
) interfaces.CustomAgentService {
|
||||
return &customAgentService{
|
||||
repo: repo,
|
||||
@@ -46,6 +50,8 @@ func NewCustomAgentService(
|
||||
kbService: kbService,
|
||||
kbShareService: kbShareService,
|
||||
wikiPageRepo: wikiPageRepo,
|
||||
tagRepo: tagRepo,
|
||||
knowledgeRepo: knowledgeRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,6 +455,7 @@ func (s *customAgentService) GetSuggestedQuestions(
|
||||
agentID string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
tagIDs []string,
|
||||
limit int,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
if limit <= 0 {
|
||||
@@ -482,6 +489,21 @@ func (s *customAgentService) GetSuggestedQuestions(
|
||||
}
|
||||
}
|
||||
|
||||
if len(tagIDs) > 0 {
|
||||
resolved, err := s.resolveKnowledgeIDsFromTags(ctx, tenantID, tagIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agentID,
|
||||
"tag_ids": tagIDs,
|
||||
})
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
knowledgeIDs = mergeUniqueStrings(knowledgeIDs, resolved)
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Determine knowledge base scope
|
||||
effectiveKBIDs := kbIDs
|
||||
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
@@ -693,6 +715,74 @@ func (s *customAgentService) GetSuggestedQuestions(
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
|
||||
func (s *customAgentService) resolveKnowledgeIDsFromTags(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
tagIDs []string,
|
||||
) ([]string, error) {
|
||||
if len(tagIDs) == 0 || s.tagRepo == nil || s.knowledgeRepo == nil {
|
||||
return nil, nil
|
||||
}
|
||||
tags, err := s.tagRepo.GetByIDs(ctx, tenantID, tagIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(tags) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
byKB := make(map[string][]string)
|
||||
for _, tag := range tags {
|
||||
byKB[tag.KnowledgeBaseID] = append(byKB[tag.KnowledgeBaseID], tag.ID)
|
||||
}
|
||||
return mergeKnowledgeIDsFromTagGroups(ctx, s.knowledgeRepo, tenantID, byKB)
|
||||
}
|
||||
|
||||
func mergeKnowledgeIDsFromTagGroups(
|
||||
ctx context.Context,
|
||||
knowledgeRepo interfaces.KnowledgeRepository,
|
||||
tenantID uint64,
|
||||
byKB map[string][]string,
|
||||
) ([]string, error) {
|
||||
seen := make(map[string]bool)
|
||||
var out []string
|
||||
for kbID, ids := range byKB {
|
||||
kids, err := knowledgeRepo.ListIDsByTagIDs(ctx, tenantID, kbID, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, kid := range kids {
|
||||
if !seen[kid] {
|
||||
seen[kid] = true
|
||||
out = append(out, kid)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func mergeUniqueStrings(base, extra []string) []string {
|
||||
if len(extra) == 0 {
|
||||
return base
|
||||
}
|
||||
seen := make(map[string]bool, len(base)+len(extra))
|
||||
out := make([]string, 0, len(base)+len(extra))
|
||||
for _, s := range base {
|
||||
if s == "" || seen[s] {
|
||||
continue
|
||||
}
|
||||
seen[s] = true
|
||||
out = append(out, s)
|
||||
}
|
||||
for _, s := range extra {
|
||||
if s == "" || seen[s] {
|
||||
continue
|
||||
}
|
||||
seen[s] = true
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// truncateQuestions truncates the question list to the specified limit
|
||||
func (s *customAgentService) truncateQuestions(questions []types.SuggestedQuestion, limit int) []types.SuggestedQuestion {
|
||||
if len(questions) > limit {
|
||||
|
||||
@@ -331,7 +331,7 @@ func (s *embedChannelService) SuggestedQuestions(
|
||||
limit = 6
|
||||
}
|
||||
kbIDs := s.resolveKnowledgeBaseIDs(ctx, ch)
|
||||
return s.agentService.GetSuggestedQuestions(ctx, ch.AgentID, kbIDs, nil, limit)
|
||||
return s.agentService.GetSuggestedQuestions(ctx, ch.AgentID, kbIDs, nil, nil, limit)
|
||||
}
|
||||
|
||||
// EmbedDisplayTitle resolves the human-readable title for embed sessions and UI chrome.
|
||||
|
||||
@@ -857,10 +857,10 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, authoriz
|
||||
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant and shared knowledge bases.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
|
||||
func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error) {
|
||||
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
if !ok {
|
||||
return nil, false, werrors.NewUnauthorizedError("Tenant ID not found in context")
|
||||
return nil, false, 0, werrors.NewUnauthorizedError("Tenant ID not found in context")
|
||||
}
|
||||
|
||||
scopes := make([]types.KnowledgeSearchScope, 0)
|
||||
@@ -896,15 +896,15 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
|
||||
}
|
||||
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
return nil, false, 0, nil
|
||||
}
|
||||
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
}
|
||||
|
||||
// SearchKnowledgeForScopes searches knowledge within the given scopes (e.g. for shared agent context).
|
||||
func (s *knowledgeService) SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error) {
|
||||
func (s *knowledgeService) SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error) {
|
||||
if len(scopes) == 0 {
|
||||
return nil, false, nil
|
||||
return nil, false, 0, nil
|
||||
}
|
||||
return s.repo.SearchKnowledgeInScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
}
|
||||
|
||||
@@ -245,6 +245,37 @@ func (s *sessionService) buildAgentConfig(
|
||||
} else {
|
||||
agentConfig.AllowedTools = tools.DefaultAllowedTools()
|
||||
}
|
||||
if len(req.SkillNames) > 0 && agentConfig.SkillsEnabled && customAgent != nil {
|
||||
switch customAgent.Config.SkillsSelectionMode {
|
||||
case "selected":
|
||||
agentConfig.AllowedSkills = intersectPreservingRequestOrder(req.SkillNames, agentConfig.AllowedSkills)
|
||||
if len(agentConfig.AllowedSkills) == 0 {
|
||||
agentConfig.SkillsEnabled = false
|
||||
}
|
||||
case "all":
|
||||
agentConfig.AllowedSkills = dedupPreservingOrder(req.SkillNames)
|
||||
}
|
||||
logger.Infof(ctx, "Applied per-request @skill scope: requested=%v effective=%v", req.SkillNames, agentConfig.AllowedSkills)
|
||||
}
|
||||
if len(req.MCPServiceIDs) > 0 {
|
||||
mentioned := dedupPreservingOrder(req.MCPServiceIDs)
|
||||
switch agentConfig.MCPSelectionMode {
|
||||
case "selected":
|
||||
narrowed := intersectPreservingRequestOrder(mentioned, customAgent.Config.MCPServices)
|
||||
if len(narrowed) > 0 {
|
||||
agentConfig.MCPServices = narrowed
|
||||
} else {
|
||||
// Explicit @mention outside agent preset — still honor user intent.
|
||||
agentConfig.MCPServices = mentioned
|
||||
}
|
||||
default:
|
||||
// "all", "none", or unset: per-request @mention narrows registration.
|
||||
agentConfig.MCPSelectionMode = "selected"
|
||||
agentConfig.MCPServices = mentioned
|
||||
}
|
||||
logger.Infof(ctx, "Applied per-request @MCP scope: requested=%v mode=%s effective=%v",
|
||||
req.MCPServiceIDs, agentConfig.MCPSelectionMode, agentConfig.MCPServices)
|
||||
}
|
||||
|
||||
// Use custom agent's system prompt if specified
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
@@ -273,15 +304,19 @@ func (s *sessionService) buildAgentConfig(
|
||||
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, req.Session.ID)
|
||||
|
||||
// Log knowledge bases if present
|
||||
if len(agentConfig.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v",
|
||||
len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases)
|
||||
if len(agentConfig.KnowledgeBases) > 0 || len(req.TagScopes) > 0 {
|
||||
if len(agentConfig.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v",
|
||||
len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases)
|
||||
} else {
|
||||
logger.Infof(ctx, "Agent configured with %d tag-scoped search target(s)", len(req.TagScopes))
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
|
||||
}
|
||||
|
||||
// Build search targets using agent's tenant (handler has validated access for shared agent)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs, req.TagScopes)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets for agent: %v", err)
|
||||
}
|
||||
@@ -292,9 +327,48 @@ func (s *sessionService) buildAgentConfig(
|
||||
agentConfig.MaxContextTokens = types.DefaultMaxContextTokens
|
||||
}
|
||||
|
||||
if len(req.MCPServiceIDs) > 0 {
|
||||
agentConfig.PinnedMCPServiceIDs = dedupPreservingOrder(req.MCPServiceIDs)
|
||||
}
|
||||
if len(req.SkillNames) > 0 {
|
||||
agentConfig.PinnedSkillNames = dedupPreservingOrder(req.SkillNames)
|
||||
}
|
||||
|
||||
return agentConfig, nil
|
||||
}
|
||||
|
||||
func intersectPreservingRequestOrder(requested []string, allowed []string) []string {
|
||||
allowedSet := make(map[string]bool, len(allowed))
|
||||
for _, value := range allowed {
|
||||
if value != "" {
|
||||
allowedSet[value] = true
|
||||
}
|
||||
}
|
||||
result := make([]string, 0, len(requested))
|
||||
seen := make(map[string]bool, len(requested))
|
||||
for _, value := range requested {
|
||||
if value == "" || seen[value] || !allowedSet[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func dedupPreservingOrder(values []string) []string {
|
||||
result := make([]string, 0, len(values))
|
||||
seen := make(map[string]bool, len(values))
|
||||
for _, value := range values {
|
||||
if value == "" || seen[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// configureSkillsFromAgent configures skills settings in AgentConfig based on CustomAgentConfig
|
||||
// Returns the skill directories and allowed skills based on the selection mode:
|
||||
// - "all": uses all preloaded skills
|
||||
|
||||
@@ -84,7 +84,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
retrievalTenantID := s.resolveRetrievalTenantID(ctx, req)
|
||||
|
||||
// Build unified search targets (computed once, used throughout pipeline)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, retrievalTenantID, knowledgeBaseIDs, knowledgeIDs)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, retrievalTenantID, knowledgeBaseIDs, knowledgeIDs, req.TagScopes)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets: %v", err)
|
||||
}
|
||||
@@ -431,6 +431,7 @@ func (s *sessionService) buildSearchTargets(
|
||||
tenantID uint64,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
tagScopes []types.TagScope,
|
||||
) (types.SearchTargets, error) {
|
||||
var targets types.SearchTargets
|
||||
|
||||
@@ -517,7 +518,55 @@ func (s *sessionService) buildSearchTargets(
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB, kbTenantMap=%v",
|
||||
if len(tagScopes) > 0 {
|
||||
tagKBIDs := make([]string, 0, len(tagScopes))
|
||||
for _, scope := range tagScopes {
|
||||
if scope.KnowledgeBaseID != "" && !fullKBSet[scope.KnowledgeBaseID] {
|
||||
tagKBIDs = append(tagKBIDs, scope.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
kbByID := make(map[string]*types.KnowledgeBase, len(tagKBIDs))
|
||||
if len(tagKBIDs) > 0 {
|
||||
if kbs, err := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, tagKBIDs); err == nil {
|
||||
for _, kb := range kbs {
|
||||
if kb != nil {
|
||||
kbByID[kb.ID] = kb
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
userID, _ := types.UserIDFromContext(ctx)
|
||||
for _, scope := range tagScopes {
|
||||
if scope.KnowledgeBaseID == "" || len(scope.TagIDs) == 0 || fullKBSet[scope.KnowledgeBaseID] {
|
||||
continue
|
||||
}
|
||||
kbTenant := kbTenantMap[scope.KnowledgeBaseID]
|
||||
if kbTenant == 0 {
|
||||
kb := kbByID[scope.KnowledgeBaseID]
|
||||
if kb == nil || kb.TenantID == tenantID {
|
||||
kbTenant = tenantID
|
||||
} else if s.kbShareService != nil && userID != "" {
|
||||
hasAccess, _ := s.kbShareService.HasTenantKBPermission(ctx, scope.KnowledgeBaseID, tenantID, callerTenantRole, types.OrgRoleViewer)
|
||||
if hasAccess {
|
||||
kbTenant = kb.TenantID
|
||||
} else {
|
||||
kbTenant = tenantID
|
||||
}
|
||||
} else {
|
||||
kbTenant = tenantID
|
||||
}
|
||||
kbTenantMap[scope.KnowledgeBaseID] = kbTenant
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: scope.KnowledgeBaseID,
|
||||
TenantID: kbTenant,
|
||||
TagIDs: append([]string(nil), scope.TagIDs...),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial/tag KB, kbTenantMap=%v",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs), kbTenantMap)
|
||||
|
||||
return targets, nil
|
||||
@@ -674,7 +723,7 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
|
||||
}
|
||||
|
||||
// Build unified search targets (computed once, used throughout pipeline)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, tenantID, knowledgeBaseIDs, knowledgeIDs)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, tenantID, knowledgeBaseIDs, knowledgeIDs, nil)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets: %v", err)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func (s *sessionService) resolveKnowledgeBases(
|
||||
knowledgeIDs = req.KnowledgeIDs
|
||||
customAgent := req.CustomAgent
|
||||
|
||||
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0
|
||||
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0 || len(req.TagScopes) > 0
|
||||
if customAgent != nil {
|
||||
logger.Infof(ctx, "KB resolution: hasExplicitMention=%v, RetrieveKBOnlyWhenMentioned=%v, KBSelectionMode=%s",
|
||||
hasExplicitMention, customAgent.Config.RetrieveKBOnlyWhenMentioned, customAgent.Config.KBSelectionMode)
|
||||
@@ -38,6 +38,7 @@ func (s *sessionService) resolveKnowledgeBases(
|
||||
// to prevent users from injecting KB/knowledge IDs outside the agent's configured range.
|
||||
if customAgent != nil && req.Session != nil && req.Session.TenantID != customAgent.TenantID {
|
||||
kbIDs, knowledgeIDs = s.restrictMentionsToAgentScope(ctx, customAgent, req.Session.TenantID, kbIDs, knowledgeIDs)
|
||||
req.TagScopes = s.restrictTagScopesToAgentScope(ctx, customAgent, req.Session.TenantID, req.TagScopes)
|
||||
}
|
||||
} else if customAgent != nil && customAgent.Config.RetrieveKBOnlyWhenMentioned {
|
||||
kbIDs = nil
|
||||
@@ -49,6 +50,31 @@ func (s *sessionService) resolveKnowledgeBases(
|
||||
return kbIDs, knowledgeIDs
|
||||
}
|
||||
|
||||
func (s *sessionService) restrictTagScopesToAgentScope(
|
||||
ctx context.Context,
|
||||
agent *types.CustomAgent,
|
||||
sessionTenantID uint64,
|
||||
tagScopes []types.TagScope,
|
||||
) []types.TagScope {
|
||||
if len(tagScopes) == 0 {
|
||||
return nil
|
||||
}
|
||||
allowedKBIDs := s.resolveKnowledgeBasesFromAgent(ctx, agent, sessionTenantID)
|
||||
allowedSet := make(map[string]bool, len(allowedKBIDs))
|
||||
for _, id := range allowedKBIDs {
|
||||
allowedSet[id] = true
|
||||
}
|
||||
filtered := make([]types.TagScope, 0, len(tagScopes))
|
||||
for _, scope := range tagScopes {
|
||||
if allowedSet[scope.KnowledgeBaseID] {
|
||||
filtered = append(filtered, scope)
|
||||
continue
|
||||
}
|
||||
logger.Warnf(ctx, "Blocking @mentioned tag scope for KB %s: not in shared agent's allowed scope", scope.KnowledgeBaseID)
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// resolveChatModelID resolves the effective chat model ID for a QA request.
|
||||
//
|
||||
// When an agent is selected, its model configuration must be complete and
|
||||
|
||||
@@ -559,6 +559,15 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
var tagIDs []string
|
||||
if tagIDsStr := strings.TrimSpace(c.Query("tag_ids")); tagIDsStr != "" {
|
||||
for _, id := range strings.Split(tagIDsStr, ",") {
|
||||
if trimmed := strings.TrimSpace(id); trimmed != "" {
|
||||
tagIDs = append(tagIDs, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
limit := 6
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 {
|
||||
@@ -566,10 +575,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting suggested questions for agent %s, kbIDs: %v, limit: %d",
|
||||
secutils.SanitizeForLog(id), kbIDs, limit)
|
||||
logger.Infof(ctx, "Getting suggested questions for agent %s, kbIDs: %v, tagIDs: %v, limit: %d",
|
||||
secutils.SanitizeForLog(id), kbIDs, tagIDs, limit)
|
||||
|
||||
questions, err := h.service.GetSuggestedQuestions(ctx, id, kbIDs, knowledgeIDs, limit)
|
||||
questions, err := h.service.GetSuggestedQuestions(ctx, id, kbIDs, knowledgeIDs, tagIDs, limit)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
|
||||
@@ -1917,6 +1917,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
"success": true,
|
||||
"data": []interface{}{},
|
||||
"has_more": false,
|
||||
"total": 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -1958,7 +1959,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
agentID, removed)
|
||||
}
|
||||
}
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
knowledges, hasMore, total, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
|
||||
@@ -1968,12 +1969,13 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
"success": true,
|
||||
"data": knowledges,
|
||||
"has_more": hasMore,
|
||||
"total": total,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Default: own + shared KBs
|
||||
knowledges, hasMore, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
|
||||
knowledges, hasMore, total, err := h.kgService.SearchKnowledge(ctx, keyword, offset, limit, fileTypes)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError("Failed to search knowledge").WithDetails(err.Error()))
|
||||
@@ -1984,6 +1986,7 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
||||
"success": true,
|
||||
"data": knowledges,
|
||||
"has_more": hasMore,
|
||||
"total": total,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -62,15 +62,68 @@ func convertMentionedItems(items []MentionedItemRequest) types.MentionedItems {
|
||||
result := make(types.MentionedItems, len(items))
|
||||
for i, item := range items {
|
||||
result[i] = types.MentionedItem{
|
||||
ID: item.ID,
|
||||
Name: item.Name,
|
||||
Type: item.Type,
|
||||
KBType: item.KBType,
|
||||
ID: item.ID,
|
||||
Name: item.Name,
|
||||
Type: item.Type,
|
||||
KBType: item.KBType,
|
||||
KBID: item.KBID,
|
||||
KBName: item.KBName,
|
||||
ServiceID: item.ServiceID,
|
||||
SkillName: item.SkillName,
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func tagScopesFromMentionedItems(items []MentionedItemRequest) []types.TagScope {
|
||||
byKB := make(map[string][]string)
|
||||
seen := make(map[string]map[string]bool)
|
||||
for _, item := range items {
|
||||
if item.Type != "tag" || item.ID == "" || item.KBID == "" {
|
||||
continue
|
||||
}
|
||||
if seen[item.KBID] == nil {
|
||||
seen[item.KBID] = make(map[string]bool)
|
||||
}
|
||||
if seen[item.KBID][item.ID] {
|
||||
continue
|
||||
}
|
||||
seen[item.KBID][item.ID] = true
|
||||
byKB[item.KBID] = append(byKB[item.KBID], item.ID)
|
||||
}
|
||||
scopes := make([]types.TagScope, 0, len(byKB))
|
||||
for kbID, tagIDs := range byKB {
|
||||
scopes = append(scopes, types.TagScope{KnowledgeBaseID: kbID, TagIDs: tagIDs})
|
||||
}
|
||||
return scopes
|
||||
}
|
||||
|
||||
func mentionedIDsByType(items []MentionedItemRequest, itemType string) []string {
|
||||
seen := make(map[string]bool)
|
||||
result := make([]string, 0)
|
||||
for _, item := range items {
|
||||
if item.Type != itemType || item.ID == "" || seen[item.ID] {
|
||||
continue
|
||||
}
|
||||
seen[item.ID] = true
|
||||
result = append(result, item.ID)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func dedupRequestStrings(values []string) []string {
|
||||
seen := make(map[string]bool, len(values))
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if value == "" || seen[value] {
|
||||
continue
|
||||
}
|
||||
seen[value] = true
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// setSSEHeaders sets the standard Server-Sent Events headers
|
||||
func setSSEHeaders(c *gin.Context) {
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
|
||||
@@ -31,6 +31,10 @@ type qaRequestContext struct {
|
||||
assistantMessage *types.Message
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string
|
||||
tagScopes []types.TagScope
|
||||
tagIDs []string
|
||||
mcpServiceIDs []string
|
||||
skillNames []string
|
||||
summaryModelID string
|
||||
webSearchEnabled bool
|
||||
enableMemory bool // Whether memory feature is enabled
|
||||
@@ -59,6 +63,9 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {
|
||||
CustomAgent: rc.customAgent,
|
||||
KnowledgeBaseIDs: rc.knowledgeBaseIDs,
|
||||
KnowledgeIDs: rc.knowledgeIDs,
|
||||
TagScopes: rc.tagScopes,
|
||||
MCPServiceIDs: rc.mcpServiceIDs,
|
||||
SkillNames: rc.skillNames,
|
||||
ImageURLs: imageURLs,
|
||||
ImageDescription: imageDescription,
|
||||
UserMessageID: rc.userMessageID,
|
||||
@@ -240,6 +247,11 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
// had memory enabled in practice, keep that behaviour.
|
||||
enableMemory := h.resolveEnableMemory(ctx, request.EnableMemory)
|
||||
|
||||
tagScopes := tagScopesFromMentionedItems(request.MentionedItems)
|
||||
tagIDs := dedupRequestStrings(append(request.TagIDs, mentionedIDsByType(request.MentionedItems, "tag")...))
|
||||
mcpServiceIDs := dedupRequestStrings(append(request.MCPServiceIDs, mentionedIDsByType(request.MentionedItems, "mcp")...))
|
||||
skillNames := dedupRequestStrings(append(request.SkillNames, mentionedIDsByType(request.MentionedItems, "skill")...))
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
ctx: ctx,
|
||||
@@ -259,6 +271,10 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
tagScopes: tagScopes,
|
||||
tagIDs: secutils.SanitizeForLogArray(tagIDs),
|
||||
mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs),
|
||||
skillNames: secutils.SanitizeForLogArray(skillNames),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
enableMemory: enableMemory,
|
||||
@@ -887,6 +903,10 @@ func (h *Handler) persistLastRequestState(parentCtx context.Context, reqCtx *qaR
|
||||
ModelID: reqCtx.summaryModelID,
|
||||
KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs,
|
||||
KnowledgeIDs: reqCtx.knowledgeIDs,
|
||||
TagIDs: reqCtx.tagIDs,
|
||||
MCPServiceIDs: reqCtx.mcpServiceIDs,
|
||||
SkillNames: reqCtx.skillNames,
|
||||
MentionedItems: reqCtx.mentionedItems,
|
||||
WebSearchEnabled: reqCtx.webSearchEnabled,
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,14 @@ type GenerateTitleRequest struct {
|
||||
|
||||
// MentionedItemRequest represents a mentioned item in the request
|
||||
type MentionedItemRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // "kb" for knowledge base, "file" for file
|
||||
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // "kb", "file", "tag", "mcp", "skill"
|
||||
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
|
||||
KBID string `json:"kb_id"` // Parent knowledge base for file/tag mentions
|
||||
KBName string `json:"kb_name"` // Display name for parent KB
|
||||
ServiceID string `json:"service_id"` // Parent MCP service for MCP tool mentions
|
||||
SkillName string `json:"skill_name"` // Preloaded agent skill name
|
||||
}
|
||||
|
||||
// ImageAttachment represents an image in a chat request.
|
||||
@@ -45,6 +49,9 @@ type CreateKnowledgeQARequest struct {
|
||||
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its tenant from share relation)
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
|
||||
SkillNames []string `json:"skill_names"` // Per-request Skills selected via @mention
|
||||
TagIDs []string `json:"tag_ids"` // @mentioned tag IDs (display/debug; scoped via MentionedItems)
|
||||
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
|
||||
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
|
||||
// EnableMemory is the per-request override for the memory feature.
|
||||
|
||||
@@ -47,6 +47,9 @@ type AgentConfig struct {
|
||||
|
||||
// Runtime-only fields (not persisted)
|
||||
VLMModelID string `json:"-"` // VLM model ID for tool result image analysis (set from CustomAgent config)
|
||||
// Per-request @mention pins (runtime only; injected as <must_use> in the user message).
|
||||
PinnedMCPServiceIDs []string `json:"-"`
|
||||
PinnedSkillNames []string `json:"-"`
|
||||
// LLM call timeout in seconds (default: 120). Controls the maximum time for a single LLM call.
|
||||
LLMCallTimeout int `json:"llm_call_timeout,omitempty"`
|
||||
|
||||
|
||||
@@ -165,10 +165,14 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
if t != nil {
|
||||
kidsCopy := make([]string, len(t.KnowledgeIDs))
|
||||
copy(kidsCopy, t.KnowledgeIDs)
|
||||
tagIDsCopy := make([]string, len(t.TagIDs))
|
||||
copy(tagIDsCopy, t.TagIDs)
|
||||
searchTargets[i] = &SearchTarget{
|
||||
Type: t.Type,
|
||||
KnowledgeBaseID: t.KnowledgeBaseID,
|
||||
TenantID: t.TenantID,
|
||||
KnowledgeIDs: kidsCopy,
|
||||
TagIDs: tagIDsCopy,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,11 +73,12 @@ type CustomAgentService interface {
|
||||
// - agentID: Agent ID
|
||||
// - kbIDs: Optional knowledge base IDs to override agent config
|
||||
// - knowledgeIDs: Optional knowledge item IDs to further filter
|
||||
// - tagIDs: Optional knowledge tag IDs; resolved to knowledge item IDs (OR semantics)
|
||||
// - limit: Maximum number of questions to return
|
||||
// Returns:
|
||||
// - List of suggested questions
|
||||
// - Possible errors
|
||||
GetSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, limit int) ([]types.SuggestedQuestion, error)
|
||||
GetSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, tagIDs []string, limit int) ([]types.SuggestedQuestion, error)
|
||||
}
|
||||
|
||||
// CustomAgentRepository defines the custom agent repository interface
|
||||
|
||||
@@ -194,9 +194,9 @@ type KnowledgeService interface {
|
||||
UpdateLastFAQImportResultDisplayStatus(ctx context.Context, kbID string, displayStatus string) error
|
||||
// SearchKnowledge searches knowledge items by keyword across the tenant.
|
||||
// fileTypes: optional list of file extensions to filter by (e.g., ["csv", "xlsx"])
|
||||
SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
SearchKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error)
|
||||
// SearchKnowledgeForScopes searches knowledge within the given (tenant_id, kb_id) scopes (e.g. for shared agent context).
|
||||
SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
SearchKnowledgeForScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error)
|
||||
}
|
||||
|
||||
// KnowledgeRepository defines the interface for knowledge repositories.
|
||||
@@ -262,7 +262,7 @@ type KnowledgeRepository interface {
|
||||
// Used by data source sync to locate existing items by external_id.
|
||||
FindByMetadataKey(ctx context.Context, tenantID uint64, kbID string, key string, value string) (*types.Knowledge, error)
|
||||
// SearchKnowledgeInScopes searches knowledge items by keyword within the given (tenant_id, kb_id) scopes (own + shared).
|
||||
SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, error)
|
||||
SearchKnowledgeInScopes(ctx context.Context, scopes []types.KnowledgeSearchScope, keyword string, offset, limit int, fileTypes []string) ([]*types.Knowledge, bool, int64, error)
|
||||
// ListIDsByTagIDs returns all knowledge IDs that have any of the specified tag IDs (OR semantics).
|
||||
ListIDsByTagIDs(ctx context.Context, tenantID uint64, kbID string, tagIDs []string) ([]string, error)
|
||||
// SetKnowledgeTags replaces all tags for a single knowledge entry (deletes old, inserts new).
|
||||
|
||||
@@ -24,10 +24,14 @@ type History struct {
|
||||
|
||||
// MentionedItem represents a mentioned knowledge base or file
|
||||
type MentionedItem struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // "kb" for knowledge base, "file" for file
|
||||
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // "kb", "file", "tag", "mcp", "skill"
|
||||
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
|
||||
KBID string `json:"kb_id"` // Parent knowledge base for file/tag mentions
|
||||
KBName string `json:"kb_name"` // Display name for parent KB
|
||||
ServiceID string `json:"service_id"` // Parent MCP service for MCP tool mentions
|
||||
SkillName string `json:"skill_name"` // Preloaded agent skill name
|
||||
}
|
||||
|
||||
// MessageImage represents an image attached to a chat message
|
||||
@@ -211,7 +215,7 @@ type Message struct {
|
||||
// Empty for non-retrieval intents or assistant messages.
|
||||
RenderedContent string `json:"-" gorm:"type:text;column:rendered_content;default:''"`
|
||||
// Channel indicates the source channel of this message (e.g., "web", "api", "im")
|
||||
Channel string `json:"channel,omitempty" gorm:"type:varchar(50);default:''"`
|
||||
Channel string `json:"channel,omitempty" gorm:"type:varchar(50);default:''"`
|
||||
// KnowledgeID links this message to a Knowledge entry in the chat history knowledge base
|
||||
// Used for vector search indexing: when set, the message content has been indexed as a Knowledge passage
|
||||
KnowledgeID string `json:"knowledge_id,omitempty" gorm:"type:varchar(36);index"`
|
||||
|
||||
@@ -4,18 +4,21 @@ package types
|
||||
// replacing the previous 14-parameter method signatures.
|
||||
// EventBus is passed separately to avoid circular dependency with the event package.
|
||||
type QARequest struct {
|
||||
Session *Session // The conversation session
|
||||
Query string // User query text
|
||||
AssistantMessageID string // Pre-created assistant message ID
|
||||
SummaryModelID string // Optional model override; empty = use agent/KB default
|
||||
CustomAgent *CustomAgent // Optional custom agent for config override
|
||||
KnowledgeBaseIDs []string // Knowledge base IDs to search (from request + @mentions)
|
||||
KnowledgeIDs []string // Specific knowledge (file) IDs to search
|
||||
ImageURLs []string // Image URLs for multimodal input
|
||||
ImageDescription string // VLM-generated image description (fallback for non-vision models)
|
||||
UserMessageID string // Created user message ID
|
||||
WebSearchEnabled bool // Whether web search is enabled for this request
|
||||
EnableMemory bool // Whether memory feature is enabled
|
||||
QuotedContext string // Quoted message content from IM quote-reply (appended at LLM prompt stage, not used for retrieval)
|
||||
Session *Session // The conversation session
|
||||
Query string // User query text
|
||||
AssistantMessageID string // Pre-created assistant message ID
|
||||
SummaryModelID string // Optional model override; empty = use agent/KB default
|
||||
CustomAgent *CustomAgent // Optional custom agent for config override
|
||||
KnowledgeBaseIDs []string // Knowledge base IDs to search (from request + @mentions)
|
||||
KnowledgeIDs []string // Specific knowledge (file) IDs to search
|
||||
TagScopes []TagScope // Tag-constrained KB scopes from @mentions
|
||||
MCPServiceIDs []string // Per-request MCP service IDs from @mentions
|
||||
SkillNames []string // Per-request preloaded skill names from @mentions
|
||||
ImageURLs []string // Image URLs for multimodal input
|
||||
ImageDescription string // VLM-generated image description (fallback for non-vision models)
|
||||
UserMessageID string // Created user message ID
|
||||
WebSearchEnabled bool // Whether web search is enabled for this request
|
||||
EnableMemory bool // Whether memory feature is enabled
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,12 @@ const (
|
||||
SearchTargetTypeKnowledge SearchTargetType = "knowledge"
|
||||
)
|
||||
|
||||
// TagScope represents a tag-constrained retrieval scope inside one knowledge base.
|
||||
type TagScope struct {
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
TagIDs []string `json:"tag_ids"`
|
||||
}
|
||||
|
||||
// SearchTarget represents a unified search target
|
||||
// Either search an entire knowledge base, or specific knowledge files within a knowledge base
|
||||
type SearchTarget struct {
|
||||
@@ -28,6 +34,8 @@ type SearchTarget struct {
|
||||
// KnowledgeIDs is the list of specific knowledge IDs to search within the knowledge base
|
||||
// Only used when Type is SearchTargetTypeKnowledge
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
// TagIDs limits retrieval to chunks/documents carrying any of these KB-local tags.
|
||||
TagIDs []string `json:"tag_ids,omitempty"`
|
||||
}
|
||||
|
||||
// SearchTargets is a list of search targets, pre-computed at request entry point
|
||||
|
||||
@@ -199,12 +199,16 @@ func (c *SummaryConfig) Scan(value interface{}) error {
|
||||
// to the frontend by GetSession so the chat input can restore the same agent,
|
||||
// model, KB scope, etc. the user had selected last time.
|
||||
type SessionLastRequestState struct {
|
||||
AgentID string `json:"agent_id,omitempty"`
|
||||
AgentEnabled bool `json:"agent_enabled"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
WebSearchEnabled bool `json:"web_search_enabled"`
|
||||
AgentID string `json:"agent_id,omitempty"`
|
||||
AgentEnabled bool `json:"agent_enabled"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
TagIDs []string `json:"tag_ids,omitempty"`
|
||||
MCPServiceIDs []string `json:"mcp_service_ids,omitempty"`
|
||||
SkillNames []string `json:"skill_names,omitempty"`
|
||||
MentionedItems MentionedItems `json:"mentioned_items,omitempty"`
|
||||
WebSearchEnabled bool `json:"web_search_enabled"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer for SessionLastRequestState (JSONB).
|
||||
|
||||
Reference in New Issue
Block a user