Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(agent): remove query display from DatabaseQuery component and update tool result structure
wizardchene138e0c81a91
diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.tsindex aeb85481c..844df7014 100644--- a/frontend/src/types/tool-results.ts+++ b/frontend/src/types/tool-results.ts@@ -154,7 +154,6 @@ export interface DatabaseQueryData {columns: string[];rows: Array<Record<string, any>>;row_count: number;- query: string;}// Web search result itemdiff --git a/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue b/frontend/src/views/chat/components/tool-results/DatabaseQuery.vueindex 48e81c201..d7f67d86f 100644--- a/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue+++ b/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue@@ -1,17 +1,6 @@<template><div class="database-query-display">- <!-- Query Display -->- <div v-if="data.query" class="query-section">- <div class="section-header">{{ $t('chat.sqlQueryExecuted') }}</div>- <pre class="query-code">{{ data.query }}</pre>- </div>-<!-- Results Summary -->- <div class="results-summary">- <strong>{{ $t('chat.sqlResultsLabel') }}</strong> {{ data.row_count }} {{ $t('chat.rowsLabel') }}- <span v-if="data.columns"> × {{ data.columns.length }} {{ $t('chat.columnsLabel') }}</span>- </div>-<!-- Results Table --><div v-if="data.rows && data.rows.length > 0" class="results-table-container"><table class="results-table">@@ -65,31 +54,6 @@ const formatValue = (value: any): string => {color: var(--td-text-color-primary);}-.query-section {- margin-bottom: 16px;-}--.section-header {- font-weight: 600;- color: var(--td-text-color-primary);- margin-bottom: 8px;- font-size: 13px;-}--.query-code {- background: var(--td-bg-color-container);- color: var(--td-text-color-primary);- padding: 12px;- border-radius: 6px;- overflow-x: auto;- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;- font-size: 12px;- line-height: 1.5;- margin: 0;- white-space: pre-wrap;- word-break: break-word;-}-.results-summary {padding: 10px 12px;background: var(--td-brand-color-light);diff --git a/internal/agent/act.go b/internal/agent/act.goindex d4b931acb..9b0360979 100644--- a/internal/agent/act.go+++ b/internal/agent/act.go@@ -13,6 +13,53 @@ import ("github.com/Tencent/WeKnora/internal/types")+// toolDisplayNames maps internal tool names to user-friendly display labels.+var toolDisplayNames = map[string]string{+ agenttools.ToolThinking: "深度思考",+ agenttools.ToolTodoWrite: "制定计划",+ agenttools.ToolGrepChunks: "关键词搜索",+ agenttools.ToolKnowledgeSearch: "知识搜索",+ agenttools.ToolListKnowledgeChunks: "查看文档分块",+ agenttools.ToolQueryKnowledgeGraph: "查询知识图谱",+ agenttools.ToolGetDocumentInfo: "获取文档信息",+ agenttools.ToolDatabaseQuery: "查询数据",+ agenttools.ToolDataAnalysis: "数据分析",+ agenttools.ToolDataSchema: "查看数据结构",+ agenttools.ToolWebSearch: "搜索网页",+ agenttools.ToolWebFetch: "获取网页",+ agenttools.ToolFinalAnswer: "最终回答",+ agenttools.ToolExecuteSkillScript: "执行技能脚本",+ agenttools.ToolReadSkill: "读取技能",+}++// toolHintSensitiveArgs lists tools whose arguments should NOT be shown in hints+// (e.g., database_query exposes raw SQL which leaks implementation details).+var toolHintSensitiveArgs = map[string]bool{+ agenttools.ToolDatabaseQuery: true,+}++// formatToolHint returns a concise human-readable hint for a tool call, e.g. `搜索网页("query text")`.+// Uses display names instead of internal tool names, and hides sensitive arguments.+func formatToolHint(name string, args map[string]any) string {+ displayName := name+ if dn, ok := toolDisplayNames[name]; ok {+ displayName = dn+ }++ if len(args) == 0 || toolHintSensitiveArgs[name] {+ return displayName+ }+ for _, v := range args {+ if s, ok := v.(string); ok {+ if len(s) > 40 {+ s = s[:40] + "…"+ }+ return fmt.Sprintf(`%s("%s")`, displayName, s)+ }+ }+ return displayName+}+// executeToolCalls runs every tool call in the LLM response, appending results to step.ToolCalls.// It also emits tool-call and tool-result events, and optionally runs reflection after each call.func (e *AgentEngine) executeToolCalls(@@ -59,8 +106,11 @@ func (e *AgentEngine) executeToolCalls(logger.Debugf(ctx, "%s Args: %s", toolTag, tc.Function.Arguments)toolCallStartTime := time.Now()++ // Emit tool hint for UI progress display (nanobot pattern)+ toolHint := formatToolHint(tc.Function.Name, args)e.eventBus.Emit(ctx, event.Event{- ID: tc.ID + "-tool-call",+ ID: tc.ID + "-tool-hint",Type: event.EventAgentToolCall,SessionID: sessionID,Data: event.AgentToolCallData{@@ -68,6 +118,7 @@ func (e *AgentEngine) executeToolCalls(ToolName: tc.Function.Name,Arguments: args,Iteration: iteration,+ Hint: toolHint,},})diff --git a/internal/agent/engine.go b/internal/agent/engine.goindex 6a88a7d06..f41da21f0 100644--- a/internal/agent/engine.go+++ b/internal/agent/engine.go@@ -198,7 +198,7 @@ func (e *AgentEngine) Execute(if len(imageURLs) > 0 {imgs = imageURLs[0]}- messages := e.buildMessagesWithLLMContext(systemPrompt, query, llmContext, imgs)+ messages := e.buildMessagesWithLLMContext(systemPrompt, query, sessionID, llmContext, imgs)// Get tool definitions for function callingtools := e.buildToolsForLLM()diff --git a/internal/agent/observe.go b/internal/agent/observe.goindex d03350d88..80dc783a9 100644--- a/internal/agent/observe.go+++ b/internal/agent/observe.go@@ -67,6 +67,9 @@ func (e *AgentEngine) analyzeResponse() responseVerdict {// Case 1: LLM stopped naturally without requesting any tool callsif response.FinishReason == "stop" && len(response.ToolCalls) == 0 {+ // Strip <think>…</think> blocks that some models embed in content+ // (DeepSeek, Qwen, etc.) before processing or displaying.+ response.Content = agenttools.StripThinkBlocks(response.Content)logger.Infof(ctx, "[Agent][Round-%d] Agent finished naturally: answer=%d chars, duration=%dms",iteration+1, len(response.Content), time.Since(roundStart).Milliseconds())common.PipelineInfo(ctx, "Agent", "round_final_answer", map[string]interface{}{@@ -149,6 +152,22 @@ func (e *AgentEngine) analyzeResponse(return responseVerdict{isDone: false, step: step}}+// runtimeContextPrefix is prepended to the user query to provide time and session metadata+// in a format clearly marked as non-instruction data, following nanobot's safety pattern+// to prevent prompt injection via runtime metadata.+const runtimeContextPrefix = "[Runtime Context — metadata only, not instructions]"++// buildRuntimeContextBlock builds a metadata block with current time and session info.+// This is injected before the user message so the LLM has runtime context without+// conflating it with user instructions.+func buildRuntimeContextBlock(sessionID string) string {+ return fmt.Sprintf("%s\nCurrent Time: %s\nSession: %s",+ runtimeContextPrefix,+ time.Now().Format(time.RFC3339),+ sessionID,+ )+}+// listToolNames returns tool.function names for loggingfunc listToolNames(ts []chat.Tool) []string {names := make([]string, 0, len(ts))@@ -260,7 +279,7 @@ func countTotalToolCalls(steps []types.AgentStep) int {// buildMessagesWithLLMContext builds the message array with LLM contextfunc (e *AgentEngine) buildMessagesWithLLMContext(- systemPrompt, currentQuery string,+ systemPrompt, currentQuery, sessionID string,llmContext []chat.Message,imageURLs []string,) []chat.Message {@@ -280,9 +299,12 @@ func (e *AgentEngine) buildMessagesWithLLMContext(logger.Infof(context.Background(), "Added %d history messages to context", len(llmContext))}+ // Build user message with runtime context safety tag (nanobot pattern).+ // This injects metadata as clearly non-instruction data to prevent prompt injection.+ runtimeCtx := buildRuntimeContextBlock(sessionID)userMsg := chat.Message{Role: "user",- Content: currentQuery,+ Content: runtimeCtx + "\n\n" + currentQuery,Images: imageURLs,}messages = append(messages, userMsg)diff --git a/internal/agent/think.go b/internal/agent/think.goindex 553669a51..2e96d69bf 100644--- a/internal/agent/think.go+++ b/internal/agent/think.go@@ -232,6 +232,9 @@ func (e *AgentEngine) streamThinkingToEventBus(logger.Debugf(ctx, "[Agent][Thinking] Iteration-%d completed: content=%d chars, tool_calls=%d",iteration+1, len(fullContent), len(toolCalls))+ // Strip <think>…</think> blocks that some models (DeepSeek, Qwen, etc.) embed in content.+ fullContent = agenttools.StripThinkBlocks(fullContent)+// Build responsereturn &types.ChatResponse{Content: fullContent,diff --git a/internal/agent/tools/database_query.go b/internal/agent/tools/database_query.goindex 91163d38e..d78a5fd51 100644--- a/internal/agent/tools/database_query.go+++ b/internal/agent/tools/database_query.go@@ -236,7 +236,7 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args json.RawMessage) (// Format outputlogger.Debugf(ctx, "[Tool][DatabaseQuery] Formatting query results...")- output := t.formatQueryResults(columns, results, securedSQL)+ output := t.formatQueryResults(columns, results)logger.Infof(ctx, "[Tool][DatabaseQuery] Execute completed successfully: %d rows returned", len(results))return &types.ToolResult{@@ -246,8 +246,6 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args json.RawMessage) ("columns": columns,"rows": results,"row_count": len(results),- "query": securedSQL,- "tenant_id": tenantID,"display_type": "database_query",},}, nil@@ -255,11 +253,11 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args json.RawMessage) (// validateAndSecureSQL validates the SQL query and injects tenant_id conditionsfunc (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint64) (string, error) {- // Use the new ValidateAndSecureSQL with comprehensive security optionssecuredSQL, validationResult, err := utils.ValidateAndSecureSQL(sqlQuery,utils.WithSecurityDefaults(tenantID),utils.WithSoftDeleteFilter("knowledge_bases", "knowledges", "chunks"),+ utils.WithHiddenKBFilter(),utils.WithInjectionRiskCheck(),)if err != nil {@@ -267,7 +265,6 @@ func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint6}if !validationResult.Valid {- // Build error message from validation errorsvar errMsgs []stringfor _, valErr := range validationResult.Errors {errMsgs = append(errMsgs, fmt.Sprintf("%s: %s", valErr.Type, valErr.Message))@@ -282,10 +279,8 @@ func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint6func (t *DatabaseQueryTool) formatQueryResults(columns []string,results []map[string]interface{},- query string,) string {output := "=== Query Results ===\n\n"- output += fmt.Sprintf("Executed SQL: %s\n\n", query)output += fmt.Sprintf("Returned %d rows\n\n", len(results))if len(results) == 0 {diff --git a/internal/agent/tools/strip_think.go b/internal/agent/tools/strip_think.gonew file mode 100644index 000000000..3c1b652a5--- /dev/null+++ b/internal/agent/tools/strip_think.go@@ -0,0 +1,37 @@+package tools++import "regexp"++// thinkBlockRe matches <think>…</think> blocks that some models embed in content.+// Uses (?s) flag so . matches newlines.+var thinkBlockRe = regexp.MustCompile(`(?s)<think>.*?</think>`)++// StripThinkBlocks removes <think>…</think> blocks from LLM output content.+// Some models (DeepSeek, Qwen, etc.) embed chain-of-thought reasoning inside+// <think> tags in the content field. These should be stripped before:+// - Displaying content to users+// - Storing content in agent state / context manager+// - Emitting content via EventBus+//+// Returns the cleaned string, or empty string if input is empty or becomes empty.+func StripThinkBlocks(content string) string {+ if content == "" {+ return ""+ }+ cleaned := thinkBlockRe.ReplaceAllString(content, "")+ // Trim leading/trailing whitespace that may remain after removal+ result := trimWhitespace(cleaned)+ return result+}++// trimWhitespace trims leading and trailing whitespace without importing strings.+func trimWhitespace(s string) string {+ start, end := 0, len(s)+ for start < end && (s[start] == ' ' || s[start] == '\n' || s[start] == '\r' || s[start] == '\t') {+ start+++ }+ for end > start && (s[end-1] == ' ' || s[end-1] == '\n' || s[end-1] == '\r' || s[end-1] == '\t') {+ end--+ }+ return s[start:end]+}diff --git a/internal/agent/tools/strip_think_test.go b/internal/agent/tools/strip_think_test.gonew file mode 100644index 000000000..efc3c6dff--- /dev/null+++ b/internal/agent/tools/strip_think_test.go@@ -0,0 +1,56 @@+package tools++import "testing"++func TestStripThinkBlocks(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected string+ }{+ {+ name: "no think blocks",+ input: "Hello, world!",+ expected: "Hello, world!",+ },+ {+ name: "empty string",+ input: "",+ expected: "",+ },+ {+ name: "single think block",+ input: "<think>Let me reason about this</think>The answer is 42.",+ expected: "The answer is 42.",+ },+ {+ name: "multiline think block",+ input: "<think>\nStep 1: analyze\nStep 2: solve\n</think>\nHere is my answer.",+ expected: "Here is my answer.",+ },+ {+ name: "multiple think blocks",+ input: "<think>first</think>Answer part 1. <think>second</think>Answer part 2.",+ expected: "Answer part 1. Answer part 2.",+ },+ {+ name: "only think block",+ input: "<think>just thinking</think>",+ expected: "",+ },+ {+ name: "think block with surrounding whitespace",+ input: " <think>reasoning</think> Answer ",+ expected: "Answer",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := StripThinkBlocks(tt.input)+ if result != tt.expected {+ t.Errorf("StripThinkBlocks(%q) = %q, want %q", tt.input, result, tt.expected)+ }+ })+ }+}diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex c62f15cec..08061d510 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -471,11 +471,10 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringkb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)if err != nil {logger.Warnf(ctx, "Failed to get knowledge base %s: %v", secutils.SanitizeForLog(kbID), err)- // Add fallback infokbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{ID: kbID,Name: kbID,- Type: "document", // Default type+ Type: "document",Description: "",DocCount: 0,RecentDocs: []agent.RecentDocInfo{},@@ -483,6 +482,12 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []stringcontinue}+ // Skip hidden/system-managed knowledge bases (e.g., __chat_history__)+ if kb.IsTemporary {+ logger.Debugf(ctx, "Skipping temporary knowledge base %s (%s) from prompt", kb.ID, kb.Name)+ continue+ }+// Get document count and recent documentsdocCount := 0recentDocs := []agent.RecentDocInfo{}diff --git a/internal/event/event_data.go b/internal/event/event_data.goindex d7a299c6e..c7f1718f4 100644--- a/internal/event/event_data.go+++ b/internal/event/event_data.go@@ -161,6 +161,7 @@ type AgentToolCallData struct {ToolName string `json:"tool_name"`Arguments map[string]any `json:"arguments,omitempty"`Iteration int `json:"iteration"`+ Hint string `json:"hint,omitempty"` // Human-readable tool hint, e.g. `web_search("query")`}// AgentToolResultData represents agent tool execution result datadiff --git a/internal/utils/inject.go b/internal/utils/inject.goindex 773bb13bf..55f6723d7 100644--- a/internal/utils/inject.go+++ b/internal/utils/inject.go@@ -136,6 +136,9 @@ type sqlValidator struct {// Soft delete filteringenableSoftDeleteInjection booltablesWithDeletedAt map[string]bool++ // Hidden knowledge base filtering (is_temporary = false)+ enableHiddenKBFilter bool}// ParseSQL parses a SQL statement using pg_query_go and extracts table names, select fields, and where fields@@ -598,6 +601,15 @@ func WithSoftDeleteFilter(tables ...string) SQLValidationOption {}}+// WithHiddenKBFilter excludes internal/temporary knowledge bases (is_temporary = true)+// from query results. These are system-managed KBs like __chat_history__ that should+// not be visible to end users.+func WithHiddenKBFilter() SQLValidationOption {+ return func(v *sqlValidator) {+ v.enableHiddenKBFilter = true+ }+}+// WithSecurityDefaults applies a comprehensive set of security validationsfunc WithSecurityDefaults(tenantID uint64) SQLValidationOption {return func(v *sqlValidator) {@@ -783,7 +795,7 @@ func ValidateSQL(sql string, opts ...SQLValidationOption) (*SQLParseResult, *SQL// This is a convenience function that combines validation and SQL rewritingfunc ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQLValidationResult, error) {// Parse and validate- parseResult, validationResult := ValidateSQL(sql, opts...)+ _, validationResult := ValidateSQL(sql, opts...)// If validation failed, return errorif !validationResult.Valid {@@ -804,7 +816,7 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQL}// If no SQL rewriting is enabled, return original SQL- if !validator.enableTenantInjection && !validator.enableSoftDeleteInjection {+ if !validator.enableTenantInjection && !validator.enableSoftDeleteInjection && !validator.enableHiddenKBFilter {return sql, validationResult, nil}@@ -820,20 +832,58 @@ func ValidateAndSecureSQL(sql string, opts ...SQLValidationOption) (string, *SQLreturn "", validationResult, fmt.Errorf("failed to normalize SQL: %v", err)}- // Build table map from parse result- tablesInQuery := make(map[string]string)- for _, tableName := range parseResult.TableNames {- tablesInQuery[strings.ToLower(tableName)] = strings.ToLower(tableName)- }+ // Build table→alias map from parse tree (respects SQL aliases like "kb", "k")+ tablesInQuery := extractTableAliasMap(result)// Inject tenant conditionssecuredSQL := validator.injectTenantConditions(normalizedSQL, tablesInQuery)// Inject deleted_at IS NULL conditionssecuredSQL = validator.injectSoftDeleteConditions(securedSQL, tablesInQuery)+ // Inject hidden KB filter (exclude is_temporary = true knowledge bases)+ securedSQL = validator.injectHiddenKBFilter(securedSQL, tablesInQuery)return securedSQL, validationResult, nil}+// extractTableAliasMap walks the parse tree to build a table_name→alias map.+// When a table has an alias (e.g., "knowledge_bases kb"), the map entry is+// {"knowledge_bases": "kb"}. Without an alias, both key and value are the table name.+func extractTableAliasMap(parseResult *pg_query.ParseResult) map[string]string {+ m := make(map[string]string)+ if len(parseResult.Stmts) == 0 || parseResult.Stmts[0].Stmt == nil {+ return m+ }+ selectStmt := parseResult.Stmts[0].Stmt.GetSelectStmt()+ if selectStmt == nil {+ return m+ }+ for _, fromItem := range selectStmt.FromClause {+ collectTableAliases(fromItem, m)+ }+ return m+}++// collectTableAliases recursively collects table→alias mappings from FROM clause nodes.+func collectTableAliases(node *pg_query.Node, m map[string]string) {+ if node == nil {+ return+ }+ if rv := node.GetRangeVar(); rv != nil {+ tableName := strings.ToLower(rv.Relname)+ alias := tableName+ if rv.Alias != nil && rv.Alias.Aliasname != "" {+ alias = strings.ToLower(rv.Alias.Aliasname)+ }+ m[tableName] = alias+ return+ }+ if je := node.GetJoinExpr(); je != nil {+ collectTableAliases(je.Larg, m)+ collectTableAliases(je.Rarg, m)+ return+ }+}+// InjectAndConditions injects filter conditions into a SQL statement using AND semantics.// If WHERE exists, the original WHERE predicates will be wrapped in parentheses.func InjectAndConditions(sql, filter string) string {@@ -921,6 +971,19 @@ func (v *sqlValidator) injectSoftDeleteConditions(sql string, tablesInQuery map[return InjectAndConditions(sql, strings.Join(conditions, " AND "))}+// injectHiddenKBFilter adds is_temporary = false filtering for the knowledge_bases table,+// hiding internal/system-managed KBs (e.g., __chat_history__) from query results.+func (v *sqlValidator) injectHiddenKBFilter(sql string, tablesInQuery map[string]string) string {+ if !v.enableHiddenKBFilter {+ return sql+ }+ alias, ok := tablesInQuery["knowledge_bases"]+ if !ok {+ return sql+ }+ return InjectAndConditions(sql, fmt.Sprintf("%s.is_temporary = false", alias))+}+// checkSQLInjectionRisks checks for common SQL injection patterns in WHERE clausefunc checkSQLInjectionRisks(whereClause string) []SQLValidationError {errors := make([]SQLValidationError, 0)