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
-1
View File
@@ -127,7 +127,6 @@ var toolDisplayNames = map[string]string{
agenttools.ToolDataSchema: "查看数据结构",
agenttools.ToolWebSearch: "搜索网页",
agenttools.ToolWebFetch: "获取网页",
agenttools.ToolFinalAnswer: "最终回答",
agenttools.ToolExecuteSkillScript: "执行技能脚本",
agenttools.ToolReadSkill: "读取技能",
}
+13 -2
View File
@@ -594,7 +594,7 @@ func (e *AgentEngine) runReActIteration(
return iterOutcomeBreak, nil
}
// 2. Analyze: Check for stop conditions (natural stop or final_answer tool)
// 2. Analyze: Check for stop conditions (natural stop with no tool calls)
verdict := e.analyzeResponse(ctx, response, step, state.CurrentRound, sessionID, roundStart)
if verdict.isDone {
// Guard against empty content: when the LLM stops naturally with no
@@ -607,7 +607,7 @@ func (e *AgentEngine) runReActIteration(
round, *emptyRetries, maxEmptyResponseRetries)
*messagesPtr = append(*messagesPtr, chat.Message{
Role: "user",
Content: "Please provide your answer by calling the final_answer tool.",
Content: "Please provide your complete answer now as plain text.",
})
return iterOutcomeContinue, nil
}
@@ -625,6 +625,17 @@ func (e *AgentEngine) runReActIteration(
return iterOutcomeBreak, nil
}
// This round is non-terminal (it will execute tools and loop again). Any
// plain assistant text streamed live to the answer area this round was a
// preamble (e.g. "let me search the knowledge base…"), not the final
// answer. No explicit retraction signal is emitted: the agent only ends by
// stopping naturally with plain text and no tool calls, so the upcoming
// tool-call events are themselves the authoritative "that wasn't the final
// answer" marker. Both the stream handler and the UI treat any answer text
// preceding a tool call in the same stream as a preamble and relocate it
// into the steps tree. The preamble is still preserved as this round's
// Thought.
// 3. Act: Execute tool calls
e.executeToolCalls(ctx, response, &step, state.CurrentRound, sessionID, assistantMessageID)
toolCallCount = len(step.ToolCalls)
+11 -99
View File
@@ -16,13 +16,6 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
// finalAnswerParseFallback is the user-visible message surfaced when the LLM
// calls final_answer with arguments we cannot recover into an answer string
// (even after RepairJSON + regex fallback). Terminating the loop with this
// message prevents the agent from re-entering and emitting duplicate answers
// on every subsequent round — the behavior reported in issue #1008.
const finalAnswerParseFallback = "Sorry, the model's final answer could not be parsed due to malformed output. Please try again or rephrase your question."
// manageContextWindow consolidates or compresses messages if approaching the token limit.
// currentTokens is the caller's best estimate of the current context size (using
// API-reported Usage when available, falling back to BPE estimation).
@@ -68,8 +61,10 @@ type responseVerdict struct {
// analyzeResponse inspects the LLM response for stop conditions:
// - finish_reason == "stop" with no tool calls → agent is done (natural stop)
// - finish_reason == "content_filter" with no tool calls → agent is done (content filtered)
// - final_answer tool call present → agent is done (explicit tool)
//
// The agent ends a turn by stopping naturally with its answer as plain
// assistant text (there is no dedicated final_answer tool). Any round that
// still requests tool calls is non-terminal and the caller continues the loop.
// It returns a responseVerdict. If isDone is true the caller should break out of the loop.
func (e *AgentEngine) analyzeResponse(
ctx context.Context, response *types.ChatResponse,
@@ -178,92 +173,9 @@ func (e *AgentEngine) analyzeResponse(
}
}
// Case 2: final_answer tool call present.
//
// final_answer is always a terminal signal: regardless of whether we can
// parse its arguments, we must end the ReAct loop here. Otherwise the LLM
// will see the tool result in the next round, re-invoke final_answer with
// near-identical content, and surface duplicate answers to the user (see
// issue #1008). Parse with three levels of tolerance:
//
// 1. strict json.Unmarshal
// 2. RepairJSON + Unmarshal
// 3. regex best-effort extraction of the "answer" field
//
// If all three fail, terminate with a user-visible fallback message.
if len(response.ToolCalls) > 0 {
for _, tc := range response.ToolCalls {
if tc.Function.Name != agenttools.ToolFinalAnswer {
continue
}
rawArgs := tc.Function.Arguments
answer, ok := agenttools.ParseFinalAnswerArgs(rawArgs)
recovered := false
if !ok {
// Could not recover any answer text — fall back to a generic
// message so the user doesn't see a blank response.
logger.Warnf(ctx, "[Agent][Round-%d] Failed to parse final_answer args (args=%q) — "+
"terminating loop with fallback message",
iteration+1, rawArgs)
answer = finalAnswerParseFallback
} else {
recovered = true
logger.Infof(ctx, "[Agent][Round-%d] final_answer tool: answer=%d chars, duration=%dms",
iteration+1, len(answer), time.Since(roundStart).Milliseconds())
}
// Always emit the final answer content and Done=true marker to the
// event bus. When strict parsing succeeded earlier in this turn,
// streamThinkingToEventBus already streamed the answer chunks, so
// we only need the Done marker in that common case. When we fell
// back to the generic message, however, the UI has not yet seen
// any answer content — emit both Content and Done to make the
// fallback visible to the user.
answerID := generateEventID("answer-done")
if !recovered {
e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: answer,
Done: false,
},
})
}
e.eventBus.Emit(ctx, event.Event{
ID: answerID,
Type: event.EventAgentFinalAnswer,
SessionID: sessionID,
Data: event.AgentFinalAnswerData{
Content: "",
Done: true,
},
})
pipelineFields := map[string]interface{}{
"iteration": iteration,
"round": iteration + 1,
"answer_len": len(answer),
"recovered": recovered,
}
if recovered {
common.PipelineInfo(ctx, "Agent", "final_answer_tool", pipelineFields)
} else {
pipelineFields["raw_args"] = rawArgs
common.PipelineWarn(ctx, "Agent", "final_answer_tool_parse_failed", pipelineFields)
}
return responseVerdict{
isDone: true,
finalAnswer: answer,
step: step,
}
}
}
// Not done — caller should continue the loop
// Any round that still requests tool calls is non-terminal: the caller
// executes the tools and loops again. The agent only ends by stopping
// naturally (Case 1) with its answer as plain assistant text.
return responseVerdict{isDone: false, step: step}
}
@@ -307,9 +219,9 @@ func escapeXMLAttr(s string) string {
// model see exactly which KBs were in scope at the time of each historical
// turn.
//
// Per-turn communication_instruction and final_answer_instruction remind the
// model not to leak internal tool names or IDs in user-visible text, and to
// always end the turn via final_answer.
// Per-turn communication_instruction and answer_instruction remind the model
// not to leak internal tool names or IDs in user-visible text, and to end the
// turn by writing its complete answer as plain assistant text.
//
// Emitted as an XML-ish block (not free prose) so it is a visually distinct,
// non-instruction envelope that is hard to conflate with user text and
@@ -320,7 +232,7 @@ func buildRuntimeContextBlock(
docs []*SelectedDocumentInfo,
) string {
var sb strings.Builder
sb.WriteString("<runtime_context note=\"turn metadata; follow communication_instruction and final_answer_instruction\">\n")
sb.WriteString("<runtime_context note=\"turn metadata; follow communication_instruction and answer_instruction\">\n")
fmt.Fprintf(&sb, " <current_time>%s</current_time>\n", time.Now().Format(time.RFC3339))
fmt.Fprintf(&sb, " <session>%s</session>\n", escapeXMLAttr(sessionID))
@@ -357,7 +269,7 @@ func buildRuntimeContextBlock(
}
sb.WriteString(" <communication_instruction>Do not use internal tool names or identifiers in your answers or in Thought. Say \"keyword retrieval\" instead of grep_chunks, \"semantic retrieval\" instead of knowledge_search, \"browse full document\" instead of list_knowledge_chunks; likewise never expose chunk_id, knowledge_id, or other internal IDs—refer to documents by title or name.</communication_instruction>\n")
sb.WriteString(" <final_answer_instruction>When you are ready to respond, you MUST call the final_answer tool with your complete user-facing answer—never end a turn with plain assistant text or skip this step.</final_answer_instruction>\n")
sb.WriteString(" <answer_instruction>When you have gathered enough information, write your complete user-facing answer as your reply and stop—do not request any more tools in that final message. Until then, keep using tools; do not give a partial answer mid-investigation.</answer_instruction>\n")
sb.WriteString("</runtime_context>")
return sb.String()
+23 -92
View File
@@ -12,98 +12,11 @@ import (
"github.com/stretchr/testify/require"
)
// newFinalAnswerResponse builds a ChatResponse that carries a single
// final_answer tool call with the given raw JSON arguments.
func newFinalAnswerResponse(rawArgs string) *types.ChatResponse {
return &types.ChatResponse{
FinishReason: "tool_calls",
ToolCalls: []types.LLMToolCall{
{
ID: "call-1",
Type: "function",
Function: types.FunctionCall{
Name: agenttools.ToolFinalAnswer,
Arguments: rawArgs,
},
},
},
}
}
// TestAnalyzeResponse_FinalAnswer_ValidArgs guards the happy path: well-formed
// arguments must be extracted into the final answer and terminate the loop.
func TestAnalyzeResponse_FinalAnswer_ValidArgs(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
resp := newFinalAnswerResponse(`{"answer": "Here is the answer."}`)
verdict := engine.analyzeResponse(
context.Background(), resp, types.AgentStep{}, 0, "sess-1", time.Now(),
)
assert.True(t, verdict.isDone, "final_answer must terminate the loop")
assert.Equal(t, "Here is the answer.", verdict.finalAnswer)
}
// TestAnalyzeResponse_FinalAnswer_MalformedJSON_RecoveredViaRepair covers the
// common case reported in issue #1008: the LLM emits final_answer with a
// trailing comma / missing brace. RepairJSON should recover the answer and
// the loop must still terminate in this single round (not re-invoke
// final_answer in the next round).
func TestAnalyzeResponse_FinalAnswer_MalformedJSON_RecoveredViaRepair(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
resp := newFinalAnswerResponse(`{"answer": "repaired"`) // missing closing brace
verdict := engine.analyzeResponse(
context.Background(), resp, types.AgentStep{}, 0, "sess-1", time.Now(),
)
assert.True(t, verdict.isDone,
"final_answer must terminate the loop even when JSON repair is needed")
assert.Equal(t, "repaired", verdict.finalAnswer)
}
// TestAnalyzeResponse_FinalAnswer_UnrecoverableArgs_StillTerminates is the
// direct regression test for issue #1008: when the arguments are so malformed
// that even RepairJSON + regex cannot recover an answer, the loop MUST still
// terminate (with a user-visible fallback message) rather than continuing and
// letting the LLM re-emit final_answer on the next round.
func TestAnalyzeResponse_FinalAnswer_UnrecoverableArgs_StillTerminates(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
// No `answer` key at all — strict parse succeeds (returns zero-value
// answer), RepairJSON is a no-op on already-valid JSON, regex finds
// nothing. All three tiers fail to recover an answer.
resp := newFinalAnswerResponse(`{"unexpected": "field"}`)
verdict := engine.analyzeResponse(
context.Background(), resp, types.AgentStep{}, 0, "sess-1", time.Now(),
)
assert.True(t, verdict.isDone,
"final_answer must terminate the loop even when args are unrecoverable — "+
"otherwise the LLM re-emits final_answer and duplicates the answer (issue #1008)")
assert.Equal(t, finalAnswerParseFallback, verdict.finalAnswer,
"unrecoverable final_answer should surface the parse-failure fallback message")
}
// TestAnalyzeResponse_FinalAnswer_Garbage_StillTerminates exercises the most
// hostile case: completely non-JSON arguments. The loop must still terminate
// — protecting against the duplicate-answer loop reported in issue #1008.
func TestAnalyzeResponse_FinalAnswer_Garbage_StillTerminates(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
resp := newFinalAnswerResponse(`not json at all`)
verdict := engine.analyzeResponse(
context.Background(), resp, types.AgentStep{}, 0, "sess-1", time.Now(),
)
assert.True(t, verdict.isDone)
assert.Equal(t, finalAnswerParseFallback, verdict.finalAnswer)
}
// TestAnalyzeResponse_NonFinalAnswerTool_DoesNotTerminate is a regression
// guard: only final_answer is terminal. Other tool calls (e.g. thinking,
// knowledge_search) must keep the loop running.
func TestAnalyzeResponse_NonFinalAnswerTool_DoesNotTerminate(t *testing.T) {
// TestAnalyzeResponse_ToolCall_DoesNotTerminate is a regression guard: the
// agent has no dedicated terminal tool — any round that requests tool calls is
// non-terminal and must keep the loop running. The agent ends only by stopping
// naturally with its answer as plain text.
func TestAnalyzeResponse_ToolCall_DoesNotTerminate(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
resp := &types.ChatResponse{
FinishReason: "tool_calls",
@@ -127,6 +40,24 @@ func TestAnalyzeResponse_NonFinalAnswerTool_DoesNotTerminate(t *testing.T) {
"non-terminal tool calls must keep the loop running")
}
// TestAnalyzeResponse_NaturalStop_Terminates guards the sole termination path:
// finish_reason == "stop" with no tool calls ends the loop and surfaces the
// plain content as the final answer.
func TestAnalyzeResponse_NaturalStop_Terminates(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
resp := &types.ChatResponse{
FinishReason: "stop",
Content: "Here is the answer.",
}
verdict := engine.analyzeResponse(
context.Background(), resp, types.AgentStep{}, 0, "sess-1", time.Now(),
)
assert.True(t, verdict.isDone, "a natural stop with no tool calls must terminate the loop")
assert.Equal(t, "Here is the answer.", verdict.finalAnswer)
}
// TestAppendToolResults_PreservesReasoningContent verifies that the assistant
// message produced by appendToolResults carries the reasoning_content emitted
// by the model in the same round. Without this, MiMo and DeepSeek V3.2+
+6 -13
View File
@@ -227,14 +227,6 @@ 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" {
emitAnswer(chunk.Content)
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" {
@@ -272,11 +264,12 @@ func (e *AgentEngine) streamThinkingToEventBus(
return
}
// Plain content channel. This is the model's user-facing answer when
// it stops naturally (without the final_answer tool). Split out any
// inline <think> reasoning so the thought goes to the thought area
// and the genuine answer streams live into the final-answer area —
// fixing the "answer first shows under Thinking, then jumps" UX.
// Plain content channel. Streamed live to the answer area
// (optimistically rendered as the final answer). If the round turns
// out to call tools, this was a preamble; the subsequent tool-call
// events let the UI retract it from the answer area and relocate it
// into the steps. Split out any inline <think> reasoning so it goes
// to the thought area instead.
if chunk.Content != "" {
thinkPart, answerPart := splitter.Feed(chunk.Content)
if thinkPart != "" {
+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": {