refactor(agent): remove final_answer tool references and update related logic

- Eliminated all instances of the final_answer tool from the agent's configuration and logic, transitioning to a model where the agent concludes responses with plain text instead.
- Updated event handling and response analysis to reflect this change, ensuring that the agent's output is now directly delivered as text without relying on a dedicated final answer tool.
- Adjusted localization strings across multiple languages to remove references to final_answer, enhancing clarity and consistency in user-facing messages.
- Improved the overall structure of the agent's response handling to streamline the process and reduce potential confusion regarding tool usage.

refactor(agent): streamline answer handling and preamble logic

- Updated the agent's response handling to treat any text streamed before a tool call as a preamble, ensuring it is not included in the final answer.
- Removed the superseded marker logic from the event emission process, simplifying the flow of answer content and enhancing clarity in the UI.
- Adjusted the event handling to ensure that preamble segments are correctly retracted and relocated into the steps tree, improving the overall user experience.
- Enhanced the agent's internal logic to better manage answer segments and their states during streaming, leading to a more coherent response structure.
This commit is contained in:
wizardchen
2026-06-04 02:35:54 +08:00
committed by lyingbug
parent b9dde2abe8
commit d38a6efd87
31 changed files with 722 additions and 663 deletions
+2 -3
View File
@@ -52,9 +52,8 @@ type ToolRequirement struct {
// tools shouldn't silently break).
var ToolCapabilityRequirements = map[string]ToolRequirement{
// ---- base / reasoning (no KB dependency, no file consumption) ----
"thinking": {},
"todo_write": {},
"final_answer": {},
"thinking": {},
"todo_write": {},
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
"knowledge_search": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
-3
View File
@@ -18,7 +18,6 @@ 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"
@@ -58,7 +57,6 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolFinalAnswer, Label: "提交最终回答", Description: "提交最终回答给用户"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"},
@@ -85,6 +83,5 @@ func DefaultAllowedTools() []string {
ToolDatabaseQuery,
ToolDataAnalysis,
ToolDataSchema,
ToolFinalAnswer,
}
}
-150
View File
@@ -1,150 +0,0 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"regexp"
"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")
answer, ok := ParseFinalAnswerArgs(string(args))
if !ok {
logger.Errorf(ctx, "[Tool][FinalAnswer] Failed to parse args (even with repair): %s", string(args))
return &types.ToolResult{
Success: false,
Error: "Failed to parse final_answer args: malformed JSON and no recoverable answer field",
}, fmt.Errorf("malformed final_answer arguments")
}
if 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(answer))
return &types.ToolResult{
Success: true,
Output: answer,
}, nil
}
// answerRegex best-effort extracts the value of an "answer": "..." field from
// a malformed JSON string. Used as a last resort when both strict parsing and
// RepairJSON fail — this keeps the final_answer tool call terminal so the
// agent loop cannot re-enter and emit duplicate answers.
//
// The pattern handles escaped quotes inside the answer via the non-greedy
// body `(?:\\.|[^"\\])*` which consumes either an escape sequence or any
// non-quote, non-backslash char.
var answerRegex = regexp.MustCompile(`"answer"\s*:\s*"((?:\\.|[^"\\])*)"`)
// ParseFinalAnswerArgs extracts the `answer` field from the final_answer
// tool's raw arguments. It is intentionally tolerant of malformed JSON that
// LLMs sometimes emit (unescaped quotes inside the answer, trailing commas,
// truncated closing braces, etc.), applying three fallbacks in order:
//
// 1. Strict json.Unmarshal on the raw string.
// 2. RepairJSON (trailing commas, invalid escapes, bracket balance) + Unmarshal.
// 3. Regex best-effort extraction of the `"answer": "..."` field.
//
// Returns the answer string and a bool indicating whether any path succeeded
// with a non-empty answer. Callers should treat ok=false as "unrecoverable"
// and surface a fallback message to the user, but must still treat the
// tool call as terminal to avoid the agent loop re-emitting final_answer.
func ParseFinalAnswerArgs(raw string) (string, bool) {
var input FinalAnswerInput
if err := json.Unmarshal([]byte(raw), &input); err == nil && input.Answer != "" {
return input.Answer, true
}
repaired := RepairJSON(raw)
if repaired != raw {
if err := json.Unmarshal([]byte(repaired), &input); err == nil && input.Answer != "" {
return input.Answer, true
}
}
if m := answerRegex.FindStringSubmatch(raw); len(m) == 2 {
if unquoted, err := unquoteJSONString(m[1]); err == nil && unquoted != "" {
return unquoted, true
}
// Unquoting failed: the capture may contain invalid escapes. Fall back
// to returning the raw capture so the user still sees *something*.
if m[1] != "" {
return m[1], true
}
}
return "", false
}
// unquoteJSONString decodes a JSON-escaped string body (without surrounding
// quotes) into its literal form. It wraps the body in quotes and leans on
// json.Unmarshal so we get the standard escape semantics (\n, \", \uXXXX, …)
// without reimplementing them.
func unquoteJSONString(body string) (string, error) {
var out string
if err := json.Unmarshal([]byte(`"`+body+`"`), &out); err != nil {
return "", err
}
return out, nil
}
-61
View File
@@ -1,61 +0,0 @@
package tools
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestParseFinalAnswerArgs covers the three-tier recovery path used by both
// the final_answer tool and the ReAct loop's terminal detection (issue #1008).
func TestParseFinalAnswerArgs(t *testing.T) {
t.Run("strict JSON is parsed as-is", func(t *testing.T) {
got, ok := ParseFinalAnswerArgs(`{"answer": "Hello, world."}`)
assert.True(t, ok)
assert.Equal(t, "Hello, world.", got)
})
t.Run("trailing comma is recovered via RepairJSON", func(t *testing.T) {
got, ok := ParseFinalAnswerArgs(`{"answer": "Hi",}`)
assert.True(t, ok)
assert.Equal(t, "Hi", got)
})
t.Run("missing closing brace is recovered via RepairJSON", func(t *testing.T) {
got, ok := ParseFinalAnswerArgs(`{"answer": "Hi"`)
assert.True(t, ok)
assert.Equal(t, "Hi", got)
})
t.Run("invalid backslash escape is recovered via RepairJSON", func(t *testing.T) {
// LLM forgot to double-escape the regex metachar — RepairJSON should
// rewrite "\+" to "\\+" so Unmarshal succeeds.
got, ok := ParseFinalAnswerArgs(`{"answer": "C\+\+"}`)
assert.True(t, ok)
assert.Equal(t, `C\+\+`, got)
})
t.Run("unescaped inner quote is recovered via regex fallback", func(t *testing.T) {
// Neither strict parse nor RepairJSON can recover this one; the regex
// still captures the well-formed prefix up to the rogue quote.
raw := `{"answer": "She said "hello" to me"}`
got, ok := ParseFinalAnswerArgs(raw)
assert.True(t, ok)
assert.NotEmpty(t, got)
})
t.Run("missing answer field returns not ok", func(t *testing.T) {
_, ok := ParseFinalAnswerArgs(`{"other": "value"}`)
assert.False(t, ok)
})
t.Run("empty answer returns not ok", func(t *testing.T) {
_, ok := ParseFinalAnswerArgs(`{"answer": ""}`)
assert.False(t, ok)
})
t.Run("completely garbled input returns not ok", func(t *testing.T) {
_, ok := ParseFinalAnswerArgs(`not json at all`)
assert.False(t, ok)
})
}
+2 -2
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
- 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.
- When your thinking is complete, deliver your answer by writing it as your plain reply and stopping (no further tool calls). NEVER include the final answer directly in a thought.
## Parameters Explained
@@ -79,7 +79,7 @@ Each thought can build on, question, or revise previous insights as understandin
8. Verify the hypothesis based on the Chain of Thought steps
9. Repeat the process until satisfied with the solution
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`,
11. NEVER include the final answer in the thought content. When thinking is complete, deliver the final answer by writing it as your plain reply and stopping (no further tool calls)`,
schema: json.RawMessage(`{
"type": "object",
"properties": {