refactor: Update function signatures across multiple files to improve readability by adding context parameters and enhancing code structure
This commit is contained in:
@@ -71,7 +71,11 @@ func NewAgentEngine(
|
||||
|
||||
// Execute executes the agent with conversation history and streaming output
|
||||
// All events are emitted to EventBus and handled by subscribers (like Handler layer)
|
||||
func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query string, llmContext []chat.Message) (*types.AgentState, error) {
|
||||
func (e *AgentEngine) Execute(
|
||||
ctx context.Context,
|
||||
sessionID, messageID, query string,
|
||||
llmContext []chat.Message,
|
||||
) (*types.AgentState, error) {
|
||||
logger.Infof(ctx, "========== Agent Execution Started ==========")
|
||||
logger.Infof(ctx, "[Agent] SessionID: %s, MessageID: %s", sessionID, messageID)
|
||||
logger.Infof(ctx, "[Agent] User Query: %s", query)
|
||||
@@ -92,7 +96,11 @@ func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query s
|
||||
}
|
||||
|
||||
// Build system prompt using progressive RAG prompt
|
||||
systemPrompt := BuildProgressiveRAGSystemPrompt(e.knowledgeBasesInfo, e.config.WebSearchEnabled, e.systemPromptTemplate)
|
||||
systemPrompt := BuildProgressiveRAGSystemPrompt(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
logger.Debugf(ctx, "[Agent] SystemPrompt Length: %d characters", len(systemPrompt))
|
||||
logger.Debugf(ctx, "[Agent] SystemPrompt (stream)\n----\n%s\n----", systemPrompt)
|
||||
|
||||
@@ -193,7 +201,12 @@ func (e *AgentEngine) executeLoop(
|
||||
// Debug: log finish reason and tool call count from LLM
|
||||
logger.Infof(ctx, "[Agent][Round-%d] LLM response received: finish_reason=%s, tool_calls=%d, content_length=%d",
|
||||
state.CurrentRound+1, response.FinishReason, len(response.ToolCalls), len(response.Content))
|
||||
logger.Debugf(ctx, "[Agent] LLM response finish=%s, toolCalls=%d", response.FinishReason, len(response.ToolCalls))
|
||||
logger.Debugf(
|
||||
ctx,
|
||||
"[Agent] LLM response finish=%s, toolCalls=%d",
|
||||
response.FinishReason,
|
||||
len(response.ToolCalls),
|
||||
)
|
||||
if response.Content != "" {
|
||||
logger.Debugf(ctx, "[Agent][Round-%d] LLM thought content:\n%s", state.CurrentRound+1, response.Content)
|
||||
}
|
||||
@@ -229,13 +242,23 @@ func (e *AgentEngine) executeLoop(
|
||||
Done: true,
|
||||
},
|
||||
})
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms", state.CurrentRound+1, time.Since(roundStart).Milliseconds())
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Agent][Round-%d] Duration: %dms",
|
||||
state.CurrentRound+1,
|
||||
time.Since(roundStart).Milliseconds(),
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
// 3. Act: Execute tool calls if any
|
||||
if len(response.ToolCalls) > 0 {
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Executing %d tool calls...", state.CurrentRound+1, len(response.ToolCalls))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Agent][Round-%d] Executing %d tool calls...",
|
||||
state.CurrentRound+1,
|
||||
len(response.ToolCalls),
|
||||
)
|
||||
|
||||
for i, tc := range response.ToolCalls {
|
||||
logger.Infof(ctx, "[Agent][Round-%d][Tool-%d/%d] Tool: %s, ID: %s",
|
||||
@@ -483,7 +506,11 @@ func (e *AgentEngine) buildToolsForLLM() []chat.Tool {
|
||||
|
||||
// appendToolResults adds tool results to the message history following OpenAI's tool calling format
|
||||
// Also writes these messages to the context manager for persistence
|
||||
func (e *AgentEngine) appendToolResults(ctx context.Context, messages []chat.Message, step types.AgentStep) []chat.Message {
|
||||
func (e *AgentEngine) appendToolResults(
|
||||
ctx context.Context,
|
||||
messages []chat.Message,
|
||||
step types.AgentStep,
|
||||
) []chat.Message {
|
||||
// Add assistant message with tool calls (if any)
|
||||
if step.Thought != "" || len(step.ToolCalls) > 0 {
|
||||
assistantMsg := chat.Message{
|
||||
@@ -744,7 +771,11 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
|
||||
})
|
||||
|
||||
// Build messages with all context
|
||||
systemPrompt := BuildProgressiveRAGSystemPrompt(e.knowledgeBasesInfo, e.config.WebSearchEnabled, e.systemPromptTemplate)
|
||||
systemPrompt := BuildProgressiveRAGSystemPrompt(
|
||||
e.knowledgeBasesInfo,
|
||||
e.config.WebSearchEnabled,
|
||||
e.systemPromptTemplate,
|
||||
)
|
||||
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
@@ -837,7 +868,10 @@ func countTotalToolCalls(steps []types.AgentStep) int {
|
||||
}
|
||||
|
||||
// buildMessagesWithLLMContext builds the message array with LLM context
|
||||
func (e *AgentEngine) buildMessagesWithLLMContext(systemPrompt, currentQuery string, llmContext []chat.Message) []chat.Message {
|
||||
func (e *AgentEngine) buildMessagesWithLLMContext(
|
||||
systemPrompt, currentQuery string,
|
||||
llmContext []chat.Message,
|
||||
) []chat.Message {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
}
|
||||
|
||||
@@ -189,7 +189,12 @@ func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseIn
|
||||
// - {{knowledge_bases}}
|
||||
// - {{web_search_status}} -> "Enabled" or "Disabled"
|
||||
// - {{current_time}} -> current time string
|
||||
func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, currentTime string) string {
|
||||
func renderPromptPlaceholdersWithStatus(
|
||||
template string,
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
currentTime string,
|
||||
) string {
|
||||
result := renderPromptPlaceholders(template, knowledgeBases)
|
||||
status := "Disabled"
|
||||
if webSearchEnabled {
|
||||
@@ -205,7 +210,10 @@ func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*Knowl
|
||||
}
|
||||
|
||||
// BuildProgressiveRAGSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled
|
||||
func BuildProgressiveRAGSystemPromptWithWeb(knowledgeBases []*KnowledgeBaseInfo, systemPromptTemplate ...string) string {
|
||||
func BuildProgressiveRAGSystemPromptWithWeb(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
var template string
|
||||
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
|
||||
template = systemPromptTemplate[0]
|
||||
@@ -217,7 +225,10 @@ func BuildProgressiveRAGSystemPromptWithWeb(knowledgeBases []*KnowledgeBaseInfo,
|
||||
}
|
||||
|
||||
// BuildProgressiveRAGSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
|
||||
func BuildProgressiveRAGSystemPromptWithoutWeb(knowledgeBases []*KnowledgeBaseInfo, systemPromptTemplate ...string) string {
|
||||
func BuildProgressiveRAGSystemPromptWithoutWeb(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
var template string
|
||||
if len(systemPromptTemplate) > 0 && systemPromptTemplate[0] != "" {
|
||||
template = systemPromptTemplate[0]
|
||||
@@ -230,7 +241,11 @@ func BuildProgressiveRAGSystemPromptWithoutWeb(knowledgeBases []*KnowledgeBaseIn
|
||||
|
||||
// BuildProgressiveRAGSystemPrompt builds the progressive RAG system prompt based on web search status
|
||||
// This is the main function to use - it automatically selects the appropriate version
|
||||
func BuildProgressiveRAGSystemPrompt(knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, systemPromptTemplate ...string) string {
|
||||
func BuildProgressiveRAGSystemPrompt(
|
||||
knowledgeBases []*KnowledgeBaseInfo,
|
||||
webSearchEnabled bool,
|
||||
systemPromptTemplate ...string,
|
||||
) string {
|
||||
if webSearchEnabled {
|
||||
return BuildProgressiveRAGSystemPromptWithWeb(knowledgeBases, systemPromptTemplate...)
|
||||
}
|
||||
|
||||
@@ -373,7 +373,11 @@ func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string) (string, error
|
||||
}
|
||||
|
||||
// formatQueryResults formats query results into readable text
|
||||
func (t *DatabaseQueryTool) formatQueryResults(columns []string, results []map[string]interface{}, query string) string {
|
||||
func (t *DatabaseQueryTool) formatQueryResults(
|
||||
columns []string,
|
||||
results []map[string]interface{},
|
||||
query string,
|
||||
) string {
|
||||
output := "=== 查询结果 ===\n\n"
|
||||
output += fmt.Sprintf("执行的SQL: %s\n\n", query)
|
||||
output += fmt.Sprintf("返回 %d 行数据\n\n", len(results))
|
||||
|
||||
@@ -133,10 +133,11 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args map[string]inter
|
||||
}
|
||||
|
||||
// Get chunk count
|
||||
_, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(ctx, t.tenantID, id, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1000,
|
||||
}, []types.ChunkType{"text"}, "")
|
||||
_, total, err := t.chunkService.GetRepository().
|
||||
ListPagedChunksByKnowledgeID(ctx, t.tenantID, id, &types.Pagination{
|
||||
Page: 1,
|
||||
PageSize: 1000,
|
||||
}, []types.ChunkType{"text"}, "")
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
results[id] = &docInfo{
|
||||
|
||||
@@ -203,7 +203,12 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
|
||||
if maxResults > 0 && mmrK > maxResults {
|
||||
mmrK = maxResults
|
||||
}
|
||||
logger.Debugf(ctx, "[Tool][GrepChunks] Applying MMR: k=%d, lambda=0.7, input=%d results", mmrK, len(scoredResults))
|
||||
logger.Debugf(
|
||||
ctx,
|
||||
"[Tool][GrepChunks] Applying MMR: k=%d, lambda=0.7, input=%d results",
|
||||
mmrK,
|
||||
len(scoredResults),
|
||||
)
|
||||
mmrResults := t.applyMMR(ctx, scoredResults, patterns, mmrK, 0.7)
|
||||
if len(mmrResults) > 0 {
|
||||
finalResults = mmrResults
|
||||
@@ -252,9 +257,9 @@ func (t *GrepChunksTool) Execute(ctx context.Context, args map[string]interface{
|
||||
|
||||
type chunkWithTitle struct {
|
||||
types.Chunk
|
||||
KnowledgeTitle string `json:"knowledge_title" gorm:"column:knowledge_title"`
|
||||
MatchScore float64 `json:"match_score" gorm:"column:match_score"` // Score based on match count and position
|
||||
MatchedPatterns int `json:"matched_patterns"` // Number of unique patterns matched
|
||||
KnowledgeTitle string `json:"knowledge_title" gorm:"column:knowledge_title"`
|
||||
MatchScore float64 `json:"match_score" gorm:"column:match_score"` // Score based on match count and position
|
||||
MatchedPatterns int `json:"matched_patterns"` // Number of unique patterns matched
|
||||
TotalChunkCount int `json:"total_chunk_count" gorm:"column:total_chunk_count"`
|
||||
}
|
||||
|
||||
@@ -344,14 +349,16 @@ func (t *GrepChunksTool) formatOutput(
|
||||
patternSummaries = append(patternSummaries, fmt.Sprintf("%s=%d", pattern, count))
|
||||
}
|
||||
|
||||
output.WriteString(fmt.Sprintf("%d) knowledge_id=%s | title=%s | chunk_hits=%d | chunk_total=%d | pattern_hits=[%s]\n",
|
||||
idx+1,
|
||||
result.KnowledgeID,
|
||||
result.KnowledgeTitle,
|
||||
result.ChunkHitCount,
|
||||
result.TotalChunkCount,
|
||||
strings.Join(patternSummaries, ", "),
|
||||
))
|
||||
output.WriteString(
|
||||
fmt.Sprintf("%d) knowledge_id=%s | title=%s | chunk_hits=%d | chunk_total=%d | pattern_hits=[%s]\n",
|
||||
idx+1,
|
||||
result.KnowledgeID,
|
||||
result.KnowledgeTitle,
|
||||
result.ChunkHitCount,
|
||||
result.TotalChunkCount,
|
||||
strings.Join(patternSummaries, ", "),
|
||||
),
|
||||
)
|
||||
}
|
||||
return output.String()
|
||||
}
|
||||
@@ -553,7 +560,11 @@ func (t *GrepChunksTool) buildContentSignature(content string) string {
|
||||
}
|
||||
|
||||
// scoreChunks calculates match scores for chunks based on pattern matches
|
||||
func (t *GrepChunksTool) scoreChunks(ctx context.Context, results []chunkWithTitle, patterns []string) []chunkWithTitle {
|
||||
func (t *GrepChunksTool) scoreChunks(
|
||||
ctx context.Context,
|
||||
results []chunkWithTitle,
|
||||
patterns []string,
|
||||
) []chunkWithTitle {
|
||||
scored := make([]chunkWithTitle, len(results))
|
||||
for i := range results {
|
||||
scored[i] = results[i]
|
||||
|
||||
@@ -246,8 +246,14 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
minScore = 0.3
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f",
|
||||
topK, vectorThreshold, keywordThreshold, minScore)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Search params: top_k=%d, vector_threshold=%.2f, keyword_threshold=%.2f, min_score=%.2f",
|
||||
topK,
|
||||
vectorThreshold,
|
||||
keywordThreshold,
|
||||
minScore,
|
||||
)
|
||||
|
||||
// Execute concurrent search (hybrid search handles both vector and keyword)
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
|
||||
@@ -280,8 +286,13 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
}
|
||||
|
||||
if t.chatModel != nil && len(deduplicatedBeforeRerank) > 0 && rerankQuery != "" {
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results, queries: %v",
|
||||
t.chatModel.GetModelName(), len(deduplicatedBeforeRerank), queries)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Applying LLM-based rerank with model: %s, input: %d results, queries: %v",
|
||||
t.chatModel.GetModelName(),
|
||||
len(deduplicatedBeforeRerank),
|
||||
queries,
|
||||
)
|
||||
rerankedResults, err := t.rerankResults(ctx, rerankQuery, deduplicatedBeforeRerank)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank failed, using original results: %v", err)
|
||||
@@ -320,7 +331,12 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
|
||||
mmrK = 1
|
||||
}
|
||||
// Apply MMR with lambda=0.7 (balance between relevance and diversity)
|
||||
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Applying MMR: k=%d, lambda=0.7, input=%d results", mmrK, len(filteredResults))
|
||||
logger.Debugf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Applying MMR: k=%d, lambda=0.7, input=%d results",
|
||||
mmrK,
|
||||
len(filteredResults),
|
||||
)
|
||||
mmrResults := t.applyMMR(ctx, filteredResults, mmrK, 0.7)
|
||||
if len(mmrResults) > 0 {
|
||||
filteredResults = mmrResults
|
||||
@@ -659,7 +675,8 @@ func (t *KnowledgeSearchTool) rerankWithLLM(
|
||||
}
|
||||
|
||||
// Optimized prompt focused on retrieval matching and reranking
|
||||
prompt := fmt.Sprintf(`You are a search result reranking expert. Your task is to evaluate how well each retrieved passage matches the user's search query and information need.
|
||||
prompt := fmt.Sprintf(
|
||||
`You are a search result reranking expert. Your task is to evaluate how well each retrieved passage matches the user's search query and information need.
|
||||
|
||||
User Query: %s
|
||||
|
||||
@@ -690,7 +707,12 @@ Passage 3: X.XX
|
||||
...
|
||||
Passage %d: X.XX
|
||||
|
||||
Output only the scores, no explanations or additional text.`, query, passagesBuilder.String(), len(batch), len(batch))
|
||||
Output only the scores, no explanations or additional text.`,
|
||||
query,
|
||||
passagesBuilder.String(),
|
||||
len(batch),
|
||||
len(batch),
|
||||
)
|
||||
|
||||
messages := []chat.Message{
|
||||
{
|
||||
@@ -727,8 +749,13 @@ Output only the scores, no explanations or additional text.`, query, passagesBui
|
||||
// Parse scores from response
|
||||
batchScores, err := t.parseScoresFromResponse(response.Content, len(batch))
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to parse LLM scores for batch %d-%d: %v, using original scores",
|
||||
batchStart+1, batchEnd, err)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to parse LLM scores for batch %d-%d: %v, using original scores",
|
||||
batchStart+1,
|
||||
batchEnd,
|
||||
err,
|
||||
)
|
||||
// Use original scores for this batch on parsing error
|
||||
for i := batchStart; i < batchEnd; i++ {
|
||||
allScores[i] = results[i].Score
|
||||
@@ -862,7 +889,12 @@ func (t *KnowledgeSearchTool) rerankWithModel(
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Reranked %d results from %d original results", len(reranked), len(results))
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Reranked %d results from %d original results",
|
||||
len(reranked),
|
||||
len(results),
|
||||
)
|
||||
return reranked, nil
|
||||
}
|
||||
|
||||
@@ -1027,7 +1059,12 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ {
|
||||
meta, err := t.getFAQMetadata(ctx, result.ID, faqMetadataCache)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v", result.ID, err)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v",
|
||||
result.ID,
|
||||
err,
|
||||
)
|
||||
} else {
|
||||
faqMeta = meta
|
||||
}
|
||||
@@ -1055,7 +1092,12 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeText}, "")
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v", result.KnowledgeID, err)
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Failed to get total chunks for knowledge %s: %v",
|
||||
result.KnowledgeID,
|
||||
err,
|
||||
)
|
||||
knowledgeTotalMap[result.KnowledgeID] = 0
|
||||
} else {
|
||||
knowledgeTotalMap[result.KnowledgeID] = total
|
||||
@@ -1065,7 +1107,12 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
|
||||
// relevanceLevel := GetRelevanceLevel(result.Score)
|
||||
output += fmt.Sprintf("\nResult #%d:\n", i+1)
|
||||
output += fmt.Sprintf(" [chunk_id: %s][chunk_index: %d]\nContent: %s\n", result.ID, result.ChunkIndex, result.Content)
|
||||
output += fmt.Sprintf(
|
||||
" [chunk_id: %s][chunk_index: %d]\nContent: %s\n",
|
||||
result.ID,
|
||||
result.ChunkIndex,
|
||||
result.Content,
|
||||
)
|
||||
|
||||
if faqMeta != nil {
|
||||
if faqMeta.StandardQuestion != "" {
|
||||
@@ -1134,7 +1181,11 @@ func (t *KnowledgeSearchTool) formatOutput(
|
||||
|
||||
if len(missingRanges) == 0 {
|
||||
// No gaps found (shouldn't happen if remaining > 0, but handle it)
|
||||
output += fmt.Sprintf(" - 获取全部内容: list_knowledge_chunks(knowledge_id=\"%s\", offset=0, limit=%d)\n", knowledgeID, totalChunks)
|
||||
output += fmt.Sprintf(
|
||||
" - 获取全部内容: list_knowledge_chunks(knowledge_id=\"%s\", offset=0, limit=%d)\n",
|
||||
knowledgeID,
|
||||
totalChunks,
|
||||
)
|
||||
} else if len(missingRanges) == 1 && missingRanges[0].start == 0 && missingRanges[0].end == int(totalChunks)-1 {
|
||||
// All chunks are missing (shouldn't happen, but handle it)
|
||||
output += fmt.Sprintf(" - 获取全部内容: list_knowledge_chunks(knowledge_id=\"%s\", offset=0, limit=%d)\n", knowledgeID, totalChunks)
|
||||
@@ -1284,8 +1335,12 @@ func (t *KnowledgeSearchTool) normalizeKeywordSearchResults(ctx context.Context,
|
||||
for _, r := range keywordResults {
|
||||
r.Score = 1.0
|
||||
}
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Keyword scores have no variance, all set to 1.0: count=%d, score=%.3f",
|
||||
len(keywordResults), minS)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Keyword scores have no variance, all set to 1.0: count=%d, score=%.3f",
|
||||
len(keywordResults),
|
||||
minS,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1336,8 +1391,15 @@ func (t *KnowledgeSearchTool) normalizeKeywordSearchResults(ctx context.Context,
|
||||
r.Score = ns
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][KnowledgeSearch] Normalized keyword scores: count=%d, raw_min=%.3f, raw_max=%.3f, normalize_min=%.3f, normalize_max=%.3f",
|
||||
len(keywordResults), minS, maxS, normalizeMin, normalizeMax)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][KnowledgeSearch] Normalized keyword scores: count=%d, raw_min=%.3f, raw_max=%.3f, normalize_min=%.3f, normalize_max=%.3f",
|
||||
len(keywordResults),
|
||||
minS,
|
||||
maxS,
|
||||
normalizeMin,
|
||||
normalizeMax,
|
||||
)
|
||||
} else {
|
||||
// Fallback: all scores are the same after percentile filtering
|
||||
for _, r := range keywordResults {
|
||||
|
||||
@@ -203,7 +203,13 @@ func (t *ListKnowledgeChunksTool) buildOutput(
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
fmt.Fprintf(builder, "本次拉取: %d 条, 检索范围: %d - %d\n\n", fetched, chunks[0].ChunkIndex, chunks[len(chunks)-1].ChunkIndex)
|
||||
fmt.Fprintf(
|
||||
builder,
|
||||
"本次拉取: %d 条, 检索范围: %d - %d\n\n",
|
||||
fetched,
|
||||
chunks[0].ChunkIndex,
|
||||
chunks[len(chunks)-1].ChunkIndex,
|
||||
)
|
||||
|
||||
builder.WriteString("=== 分块内容预览 ===\n\n")
|
||||
for idx, c := range chunks {
|
||||
|
||||
@@ -177,7 +177,12 @@ func sanitizeName(name string) string {
|
||||
}
|
||||
|
||||
// RegisterMCPTools registers MCP tools from given services
|
||||
func RegisterMCPTools(ctx context.Context, registry *ToolRegistry, services []*types.MCPService, mcpManager *mcp.MCPManager) error {
|
||||
func RegisterMCPTools(
|
||||
ctx context.Context,
|
||||
registry *ToolRegistry,
|
||||
services []*types.MCPService,
|
||||
mcpManager *mcp.MCPManager,
|
||||
) error {
|
||||
if len(services) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -239,7 +244,11 @@ func RegisterMCPTools(ctx context.Context, registry *ToolRegistry, services []*t
|
||||
}
|
||||
|
||||
// GetMCPToolsInfo returns information about available MCP tools
|
||||
func GetMCPToolsInfo(ctx context.Context, services []*types.MCPService, mcpManager *mcp.MCPManager) (map[string][]string, error) {
|
||||
func GetMCPToolsInfo(
|
||||
ctx context.Context,
|
||||
services []*types.MCPService,
|
||||
mcpManager *mcp.MCPManager,
|
||||
) (map[string][]string, error) {
|
||||
result := make(map[string][]string)
|
||||
|
||||
// Use provided context with timeout
|
||||
|
||||
@@ -369,7 +369,10 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args map[string]i
|
||||
}
|
||||
|
||||
// buildGraphVisualizationData builds structured data for graph visualization
|
||||
func buildGraphVisualizationData(results []*types.SearchResult, graphConfigs map[string]map[string]interface{}) map[string]interface{} {
|
||||
func buildGraphVisualizationData(
|
||||
results []*types.SearchResult,
|
||||
graphConfigs map[string]map[string]interface{},
|
||||
) map[string]interface{} {
|
||||
// Build a simple graph structure for frontend visualization
|
||||
nodes := make([]map[string]interface{}, 0)
|
||||
edges := make([]map[string]interface{}, 0)
|
||||
|
||||
@@ -69,7 +69,11 @@ func (r *ToolRegistry) GetFunctionDefinitions() []types.FunctionDefinition {
|
||||
}
|
||||
|
||||
// ExecuteTool executes a tool by name with the given arguments
|
||||
func (r *ToolRegistry) ExecuteTool(ctx context.Context, name string, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
func (r *ToolRegistry) ExecuteTool(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
args map[string]interface{},
|
||||
) (*types.ToolResult, error) {
|
||||
common.PipelineInfo(ctx, "AgentTool", "execute_start", map[string]interface{}{
|
||||
"tool": name,
|
||||
"args": args,
|
||||
|
||||
@@ -196,7 +196,8 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
|
||||
branchKeys = append(branchKeys, k)
|
||||
}
|
||||
|
||||
incomplete := thoughtData.NextThoughtNeeded || thoughtData.NeedsMoreThoughts || thoughtData.ThoughtNumber < thoughtData.TotalThoughts
|
||||
incomplete := thoughtData.NextThoughtNeeded || thoughtData.NeedsMoreThoughts ||
|
||||
thoughtData.ThoughtNumber < thoughtData.TotalThoughts
|
||||
|
||||
responseData := map[string]interface{}{
|
||||
"thought_number": thoughtData.ThoughtNumber,
|
||||
@@ -209,7 +210,12 @@ func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]in
|
||||
"incomplete_steps": incomplete,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute completed - Thought %d/%d", thoughtData.ThoughtNumber, thoughtData.TotalThoughts)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][SequentialThinking] Execute completed - Thought %d/%d",
|
||||
thoughtData.ThoughtNumber,
|
||||
thoughtData.TotalThoughts,
|
||||
)
|
||||
|
||||
outputMsg := "Thought process recorded"
|
||||
if incomplete {
|
||||
|
||||
@@ -252,7 +252,10 @@ func (t *WebFetchTool) validateParams(p webFetchParams) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) executeFetch(ctx context.Context, params webFetchParams) (string, map[string]interface{}, error) {
|
||||
func (t *WebFetchTool) executeFetch(
|
||||
ctx context.Context,
|
||||
params webFetchParams,
|
||||
) (string, map[string]interface{}, error) {
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Fetching URL: %s", params.URL)
|
||||
|
||||
finalURL := t.normalizeGitHubURL(params.URL)
|
||||
@@ -375,14 +378,17 @@ func (t *WebFetchTool) fetchHTMLContent(ctx context.Context, targetURL string) (
|
||||
func (t *WebFetchTool) fetchWithChromedp(ctx context.Context, targetURL string) (string, error) {
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取开始 url=%s", targetURL)
|
||||
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
opts := append(
|
||||
chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", true),
|
||||
chromedp.Flag("disable-setuid-sandbox", true),
|
||||
chromedp.Flag("disable-dev-shm-usage", true),
|
||||
chromedp.Flag("disable-gpu", true),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
chromedp.Flag("disable-features", "VizDisplayCompositor"),
|
||||
chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
|
||||
chromedp.UserAgent(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
),
|
||||
)
|
||||
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx, opts...)
|
||||
@@ -435,7 +441,10 @@ func (t *WebFetchTool) fetchWithTimeout(ctx context.Context, targetURL string) (
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WebFetchTool/1.0)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8")
|
||||
req.Header.Set(
|
||||
"Accept",
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
|
||||
)
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
|
||||
|
||||
@@ -57,7 +57,10 @@ func NewWebSearchTool(
|
||||
**Parameters**:
|
||||
- query (required): Search query string
|
||||
|
||||
**Returns**: Web search results with title, URL, snippet, and content (up to ` + fmt.Sprintf("%d", maxResults) + ` results)
|
||||
**Returns**: Web search results with title, URL, snippet, and content (up to ` + fmt.Sprintf(
|
||||
"%d",
|
||||
maxResults,
|
||||
) + ` results)
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -80,7 +83,10 @@ func NewWebSearchTool(
|
||||
- Use this tool when knowledge bases don't have the information you need
|
||||
- Results include URL, title, snippet, and content snippet (may be truncated)
|
||||
- **CRITICAL**: If content is truncated or you need full details, use **web_fetch** to fetch complete page content
|
||||
- Maximum ` + fmt.Sprintf("%d", maxResults) + ` results will be returned per search`
|
||||
- Maximum ` + fmt.Sprintf(
|
||||
"%d",
|
||||
maxResults,
|
||||
) + ` results will be returned per search`
|
||||
|
||||
return &WebSearchTool{
|
||||
BaseTool: NewBaseTool("web_search", description),
|
||||
@@ -152,7 +158,12 @@ func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}
|
||||
searchConfig.MaxResults = t.maxResults
|
||||
|
||||
// Perform web search
|
||||
logger.Infof(ctx, "[Tool][WebSearch] Performing web search with provider: %s, maxResults: %d", searchConfig.Provider, searchConfig.MaxResults)
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"[Tool][WebSearch] Performing web search with provider: %s, maxResults: %d",
|
||||
searchConfig.Provider,
|
||||
searchConfig.MaxResults,
|
||||
)
|
||||
webResults, err := t.webSearchService.Search(ctx, &searchConfig, query)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][WebSearch] Web search failed: %v", err)
|
||||
@@ -165,7 +176,8 @@ func (t *WebSearchTool) Execute(ctx context.Context, args map[string]interface{}
|
||||
logger.Infof(ctx, "[Tool][WebSearch] Web search returned %d results", len(webResults))
|
||||
|
||||
// Apply RAG compression if configured
|
||||
if len(webResults) > 0 && tenant.WebSearchConfig.CompressionMethod != "none" && tenant.WebSearchConfig.CompressionMethod != "" {
|
||||
if len(webResults) > 0 && tenant.WebSearchConfig.CompressionMethod != "none" &&
|
||||
tenant.WebSearchConfig.CompressionMethod != "" {
|
||||
// Load session-scoped temp KB state from Redis using SessionService
|
||||
tempKBID, seen, ids := t.sessionService.GetWebSearchTempKBState(ctx, t.sessionID)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user