refactor(agent): remove query display from DatabaseQuery component and update tool result structure
- Removed the query display section from the DatabaseQuery component to streamline the UI. - Updated the DatabaseQueryData interface to eliminate the query field, reflecting changes in tool result handling. - Enhanced the DatabaseQuery tool execution to focus on returning structured results without exposing raw SQL queries. - Added a new utility to strip <think> blocks from LLM outputs, improving content clarity and user experience.
This commit is contained in:
+52
-1
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -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 calling
|
||||
tools := e.buildToolsForLLM()
|
||||
|
||||
@@ -67,6 +67,9 @@ func (e *AgentEngine) analyzeResponse(
|
||||
) responseVerdict {
|
||||
// Case 1: LLM stopped naturally without requesting any tool calls
|
||||
if 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 logging
|
||||
func 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 context
|
||||
func (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)
|
||||
|
||||
@@ -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 response
|
||||
return &types.ChatResponse{
|
||||
Content: fullContent,
|
||||
|
||||
@@ -236,7 +236,7 @@ func (t *DatabaseQueryTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
|
||||
// Format output
|
||||
logger.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 conditions
|
||||
func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint64) (string, error) {
|
||||
// Use the new ValidateAndSecureSQL with comprehensive security options
|
||||
securedSQL, 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 errors
|
||||
var errMsgs []string
|
||||
for _, 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 uint6
|
||||
func (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 {
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user