feat: implement final_answer tool and enhance agent duration tracking

- Introduced the final_answer tool to ensure agents submit their complete responses as the last action, improving response accuracy and consistency.
- Updated the agent engine to log detailed information about tool calls and responses, including the total duration of agent execution.
- Enhanced the chat message model to include agent_duration_ms, tracking the total execution time from query start to answer delivery.
- Implemented JSON field extraction for streaming responses, allowing for more efficient handling of tool call outputs.

These changes significantly improve the agent's response handling and ensure that final answers are consistently delivered, enhancing overall user experience.
This commit is contained in:
wizardchen
2026-03-06 12:21:23 +08:00
committed by lyingbug
parent bedb8ceb08
commit a4b255a456
21 changed files with 1311 additions and 777 deletions
+128 -17
View File
@@ -8,7 +8,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/agent/tools"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
@@ -26,7 +26,7 @@ func generateEventID(suffix string) string {
// AgentEngine is the core engine for running ReAct agents
type AgentEngine struct {
config *types.AgentConfig
toolRegistry *tools.ToolRegistry
toolRegistry *agenttools.ToolRegistry
chatModel chat.Chat
eventBus *event.EventBus
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
@@ -50,7 +50,7 @@ func listToolNames(ts []chat.Tool) []string {
func NewAgentEngine(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *tools.ToolRegistry,
toolRegistry *agenttools.ToolRegistry,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
@@ -78,7 +78,7 @@ func NewAgentEngine(
func NewAgentEngineWithSkills(
config *types.AgentConfig,
chatModel chat.Chat,
toolRegistry *tools.ToolRegistry,
toolRegistry *agenttools.ToolRegistry,
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
@@ -237,7 +237,27 @@ func (e *AgentEngine) executeLoop(
})
// 1. Think: Call LLM with function calling and stream thinking through EventBus
logger.Infof(ctx, "[Agent][Round-%d] Calling LLM with %d tools available...", state.CurrentRound+1, len(tools))
logger.Infof(ctx, "[Agent][Round-%d] Calling LLM with %d messages, %d tools", state.CurrentRound+1, len(messages), len(tools))
for i, msg := range messages {
contentPreview := msg.Content
if len(contentPreview) > 200 {
contentPreview = contentPreview[:200] + "..."
}
if msg.Role == "tool" {
logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=tool, name=%s, tool_call_id=%s, content_len=%d",
state.CurrentRound+1, i, msg.Name, msg.ToolCallID, len(msg.Content))
} else if len(msg.ToolCalls) > 0 {
tcNames := make([]string, len(msg.ToolCalls))
for j, tc := range msg.ToolCalls {
tcNames[j] = tc.Function.Name
}
logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=%s, content_len=%d, tool_calls=%v",
state.CurrentRound+1, i, msg.Role, len(msg.Content), tcNames)
} else {
logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=%s, content_len=%d, content=%s",
state.CurrentRound+1, i, msg.Role, len(msg.Content), contentPreview)
}
}
common.PipelineInfo(ctx, "Agent", "think_start", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
@@ -260,17 +280,15 @@ func (e *AgentEngine) executeLoop(
"content_len": len(response.Content),
})
// 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),
)
// Log LLM response summary
logger.Infof(ctx, "[Agent][Round-%d] LLM response: finish_reason=%s, content_len=%d, tool_calls=%d",
state.CurrentRound+1, response.FinishReason, len(response.Content), len(response.ToolCalls))
if response.Content != "" {
logger.Debugf(ctx, "[Agent][Round-%d] LLM thought content:\n%s", state.CurrentRound+1, response.Content)
logger.Infof(ctx, "[Agent][Round-%d] LLM content:\n%s", state.CurrentRound+1, response.Content)
}
for i, tc := range response.ToolCalls {
logger.Infof(ctx, "[Agent][Round-%d] tool_call[%d]: %s(%s)",
state.CurrentRound+1, i, tc.Function.Name, tc.Function.Arguments)
}
// Create agent step
@@ -313,7 +331,53 @@ func (e *AgentEngine) executeLoop(
break
}
// 3. Act: Execute tool calls if any
// 3. Check for final_answer tool call - if present, agent is done
hasFinalAnswer := false
if len(response.ToolCalls) > 0 {
for _, tc := range response.ToolCalls {
if tc.Function.Name == agenttools.ToolFinalAnswer {
var faArgs struct {
Answer string `json:"answer"`
}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &faArgs); err != nil {
logger.Warnf(ctx, "[Agent][Round-%d] Failed to parse final_answer args: %v", state.CurrentRound+1, err)
} else {
logger.Infof(ctx, "[Agent][Round-%d] final_answer tool called, answer length: %d",
state.CurrentRound+1, len(faArgs.Answer))
state.FinalAnswer = faArgs.Answer
state.IsComplete = true
hasFinalAnswer = true
// Emit answer done marker (content was already streamed via processToolCallsDelta)
e.eventBus.Emit(ctx, event.Event{
ID: generateEventID("answer-done"),
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: "",
Done: true,
},
})
common.PipelineInfo(ctx, "Agent", "final_answer_tool", map[string]interface{}{
"iteration": state.CurrentRound,
"round": state.CurrentRound + 1,
"answer_len": len(faArgs.Answer),
})
}
break
}
}
}
if hasFinalAnswer {
state.RoundSteps = append(state.RoundSteps, step)
logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms (final_answer tool)",
state.CurrentRound+1, time.Since(roundStart).Milliseconds())
break
}
// 4. Act: Execute tool calls if any
if len(response.ToolCalls) > 0 {
logger.Infof(
ctx,
@@ -664,7 +728,12 @@ func (e *AgentEngine) streamLLMToEventBus(
chunkCount++
if chunk.Content != "" {
fullContent += chunk.Content
// Only accumulate LLM's own text output, not content extracted from tool arguments
// (e.g. final_answer's answer or thinking tool's thought are streamed separately)
isExtracted := chunk.Data != nil && chunk.Data["source"] != nil
if !isExtracted {
fullContent += chunk.Content
}
}
// Collect tool calls if present
@@ -754,9 +823,12 @@ func (e *AgentEngine) streamThinkingToEventBus(
logger.Debug(context.Background(), "[Agent] streamLLM opts tool_choice=auto temperature=", e.config.Temperature)
pendingToolCalls := make(map[string]bool)
thinkingToolIDs := make(map[string]string) // tool_call_id -> event ID for thinking tool streams
// Generate a single ID for this entire thinking stream
thinkingID := generateEventID("thinking")
// Generate a single ID for final_answer streaming (if applicable)
answerID := generateEventID("answer")
logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] ThinkingID: %s", iteration+1, thinkingID)
fullContent, toolCalls, err := e.streamLLMToEventBus(
@@ -783,6 +855,45 @@ func (e *AgentEngine) streamThinkingToEventBus(
}
}
// Handle final_answer tool's streaming answer content
if chunk.ResponseType == types.ResponseTypeAnswer {
if source, _ := chunk.Data["source"].(string); source == "final_answer_tool" {
e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: chunk.Content,
Done: false,
},
})
return
}
}
// Handle thinking tool's streaming thought content
if chunk.ResponseType == types.ResponseTypeThinking && chunk.Data != nil {
if source, _ := chunk.Data["source"].(string); source == "thinking_tool" {
toolCallID, _ := chunk.Data["tool_call_id"].(string)
eventID, exists := thinkingToolIDs[toolCallID]
if !exists {
eventID = generateEventID("thinking-tool")
thinkingToolIDs[toolCallID] = eventID
}
e.eventBus.Emit(ctx, event.Event{
ID: eventID,
Type: event.EventAgentThought,
SessionID: sessionID,
Data: event.AgentThoughtData{
Content: chunk.Content,
Iteration: iteration,
Done: false,
},
})
return
}
}
if chunk.Content != "" {
// logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] Emitting thought chunk: %d chars",
// iteration+1, len(chunk.Content))
+4 -2
View File
@@ -403,12 +403,13 @@ To help users solve problems by planning, thinking, and using available tools (l
1. **Analyze:** Understand the user's request.
2. **Plan:** If the task is complex, use todo_write to create a plan.
3. **Execute:** Use available tools to gather information or perform actions.
4. **Synthesize:** Provide a comprehensive answer.
4. **Synthesize:** Call the final_answer tool with your comprehensive answer. You MUST always end by calling final_answer.
### Tool Guidelines
* **web_search / web_fetch:** Use these if enabled to find information from the internet.
* **todo_write:** Use for managing multi-step tasks.
* **thinking:** Use to plan and reflect.
* **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it.
### System Status
Current Time: {{current_time}}
@@ -460,7 +461,7 @@ If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task:
Only when ALL todo_write tasks are "completed":
* Synthesize findings from the full text of all retrieved chunks.
* Check for consistency.
* Generate the final response.
* Call the **final_answer** tool with your complete, well-formatted response. You MUST always end by calling final_answer.
### Core Retrieval Strategy (Strict Sequence)
For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:
@@ -478,6 +479,7 @@ For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:
* **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient.
* **todo_write:** Your "Manager". Tracks multi-step research.
* **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks.
* **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it.
### Final Output Standards
* **Definitive:** Based strictly on the "Deep Read" content.
+3
View File
@@ -18,6 +18,7 @@ const (
ToolDataSchema = "data_schema"
ToolWebSearch = "web_search"
ToolWebFetch = "web_fetch"
ToolFinalAnswer = "final_answer"
// Skills-related tools (only available when skills are enabled)
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
@@ -46,6 +47,7 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolFinalAnswer, Label: "提交最终回答", Description: "提交最终回答给用户"},
}
}
@@ -62,5 +64,6 @@ func DefaultAllowedTools() []string {
ToolDatabaseQuery,
ToolDataAnalysis,
ToolDataSchema,
ToolFinalAnswer,
}
}
+87
View File
@@ -0,0 +1,87 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
var finalAnswerTool = BaseTool{
name: ToolFinalAnswer,
description: `Submit your final answer to the user's question.
## When to Use This Tool
You MUST call this tool as your LAST action when you are ready to deliver your final response to the user.
After gathering all necessary information through other tools (search, retrieval, analysis, etc.),
synthesize your findings and submit the complete answer through this tool.
## Important Rules
1. NEVER end your turn without calling this tool
2. The answer parameter must contain your complete, well-formatted response
3. Include all citations, structure, and formatting in the answer
4. This should always be the last tool you call
## Parameters
- **answer**: Your complete final answer in Markdown format, including all citations and formatting`,
schema: json.RawMessage(`{
"type": "object",
"properties": {
"answer": {
"type": "string",
"description": "Your complete final answer in Markdown format. Include all citations, structure, images, and formatting."
}
},
"required": ["answer"]
}`),
}
// FinalAnswerInput defines the input parameters for the final answer tool
type FinalAnswerInput struct {
Answer string `json:"answer"`
}
// FinalAnswerTool submits the agent's final answer to the user
type FinalAnswerTool struct {
BaseTool
}
// NewFinalAnswerTool creates a new final answer tool instance
func NewFinalAnswerTool() *FinalAnswerTool {
return &FinalAnswerTool{
BaseTool: finalAnswerTool,
}
}
// Execute executes the final answer tool
func (t *FinalAnswerTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][FinalAnswer] Execute started")
var input FinalAnswerInput
if err := json.Unmarshal(args, &input); err != nil {
logger.Errorf(ctx, "[Tool][FinalAnswer] Failed to parse args: %v", err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, err
}
if input.Answer == "" {
return &types.ToolResult{
Success: false,
Error: "answer must be a non-empty string",
}, fmt.Errorf("answer must be a non-empty string")
}
logger.Infof(ctx, "[Tool][FinalAnswer] Answer length: %d characters", len(input.Answer))
return &types.ToolResult{
Success: true,
Output: input.Answer,
}, nil
}
+3 -3
View File
@@ -37,7 +37,7 @@ Each thought can build on, question, or revise previous insights as understandin
- Generates a solution hypothesis
- Verifies the hypothesis based on the Chain of Thought steps
- Repeats the process until satisfied
- Provides a correct answer
- When thinking is complete, you can call the final_answer tool to deliver your answer if all your thinking is complete. NEVER include the final answer directly in a thought.
## Parameters Explained
@@ -78,8 +78,8 @@ Each thought can build on, question, or revise previous insights as understandin
7. Generate a solution hypothesis when appropriate
8. Verify the hypothesis based on the Chain of Thought steps
9. Repeat the process until satisfied with the solution
10. Provide a single, ideally correct answer as the final output
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`,
10. Only set next_thought_needed to false when truly done and a satisfactory answer is reached
11. NEVER include the final answer in the thought content. When thinking is complete, you can call the final_answer tool to deliver the final answer to the user`,
schema: json.RawMessage(`{
"type": "object",
"properties": {