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:
@@ -127,7 +127,6 @@ var toolDisplayNames = map[string]string{
|
||||
agenttools.ToolDataSchema: "查看数据结构",
|
||||
agenttools.ToolWebSearch: "搜索网页",
|
||||
agenttools.ToolWebFetch: "获取网页",
|
||||
agenttools.ToolFinalAnswer: "最终回答",
|
||||
agenttools.ToolExecuteSkillScript: "执行技能脚本",
|
||||
agenttools.ToolReadSkill: "读取技能",
|
||||
}
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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
@@ -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 != "" {
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -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": {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -193,15 +192,20 @@ func buildAssistantHistoryMessages(m *types.Message) []chat.Message {
|
||||
return msgs
|
||||
}
|
||||
|
||||
// filterNonTerminalToolCalls drops final_answer entries since those are
|
||||
// terminal signals — the canonical answer text is replayed via the trailing
|
||||
// assistant message instead, so re-injecting final_answer here would either
|
||||
// duplicate the answer or confuse the model into thinking the previous turn
|
||||
// is still mid-flight.
|
||||
// legacyFinalAnswerToolName is the name of the now-removed final_answer tool.
|
||||
// It is retained here only to filter such calls out of OLD persisted agent
|
||||
// histories: pre-existing conversations recorded a final_answer tool call as
|
||||
// the terminal step, and the canonical answer text is replayed via the
|
||||
// trailing assistant message instead. Re-injecting it would duplicate the
|
||||
// answer or confuse the model into thinking the previous turn is mid-flight.
|
||||
const legacyFinalAnswerToolName = "final_answer"
|
||||
|
||||
// filterNonTerminalToolCalls drops legacy final_answer entries from historical
|
||||
// tool calls (see legacyFinalAnswerToolName). New turns never produce them.
|
||||
func filterNonTerminalToolCalls(calls []types.ToolCall) []types.ToolCall {
|
||||
out := make([]types.ToolCall, 0, len(calls))
|
||||
for _, tc := range calls {
|
||||
if tc.Name == agenttools.ToolFinalAnswer {
|
||||
if tc.Name == legacyFinalAnswerToolName {
|
||||
continue
|
||||
}
|
||||
out = append(out, tc)
|
||||
|
||||
@@ -148,8 +148,10 @@ func TestBuildAssistantHistoryMessages_ToolCallsExpandIntoOpenAIShape(t *testing
|
||||
Thought: "",
|
||||
ToolCalls: []types.ToolCall{
|
||||
{
|
||||
// Legacy persisted data: old conversations recorded a
|
||||
// final_answer terminal tool call. The filter still drops it.
|
||||
ID: "call_2",
|
||||
Name: agenttools.ToolFinalAnswer,
|
||||
Name: "final_answer",
|
||||
Args: map[string]interface{}{"answer": "Found 3 matches in the docs."},
|
||||
Result: &types.ToolResult{Success: true},
|
||||
},
|
||||
@@ -216,12 +218,12 @@ func TestBuildAssistantHistoryMessages_ToolFailureSurfacesAsError(t *testing.T)
|
||||
}, got[1])
|
||||
}
|
||||
|
||||
// TestFilterNonTerminalToolCalls confirms only final_answer is dropped — every
|
||||
// other tool (KB search, web search, MCP tools…) must survive the filter.
|
||||
// TestFilterNonTerminalToolCalls confirms a legacy final_answer entry is
|
||||
// dropped — every other tool (KB search, web search, MCP tools…) must survive.
|
||||
func TestFilterNonTerminalToolCalls(t *testing.T) {
|
||||
in := []types.ToolCall{
|
||||
{Name: agenttools.ToolKnowledgeSearch},
|
||||
{Name: agenttools.ToolFinalAnswer},
|
||||
{Name: "final_answer"},
|
||||
{Name: agenttools.ToolWebSearch},
|
||||
}
|
||||
out := filterNonTerminalToolCalls(in)
|
||||
|
||||
@@ -503,8 +503,7 @@ func (s *agentService) registerTools(
|
||||
// Deduplicate while preserving original order.
|
||||
allowedTools = dedupStrings(allowedTools)
|
||||
|
||||
logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)
|
||||
allowedTools = append(allowedTools, tools.ToolFinalAnswer)
|
||||
// logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)
|
||||
// Register each allowed tool
|
||||
for _, toolName := range allowedTools {
|
||||
var toolToRegister types.Tool
|
||||
@@ -559,10 +558,6 @@ func (s *agentService) registerTools(
|
||||
toolToRegister = tools.NewDataSchemaTool(s.knowledgeService, s.chunkService.GetRepository())
|
||||
logger.Infof(ctx, "Registered data_schema tool")
|
||||
|
||||
case tools.ToolFinalAnswer:
|
||||
toolToRegister = tools.NewFinalAnswerTool()
|
||||
logger.Infof(ctx, "Registered final_answer tool")
|
||||
|
||||
// Wiki tools — only registered when wiki KBs are detected
|
||||
case tools.ToolWikiReadPage:
|
||||
toolToRegister = tools.NewWikiReadPageTool(s.wikiPageService, wikiScopes)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -31,10 +32,45 @@ type AgentStreamHandler struct {
|
||||
// State tracking
|
||||
knowledgeRefs []*types.SearchResult
|
||||
finalAnswer string
|
||||
answerSegments []*answerSegment // Per-answer-event-ID accumulation, so superseded preambles can be dropped
|
||||
eventStartTimes map[string]time.Time // Track start time for duration calculation
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// answerSegment accumulates the streamed content of a single final-answer event
|
||||
// ID. A non-terminal round may stream a preamble ("let me search…") under its
|
||||
// own answer ID and then be marked superseded once the round turns out to call
|
||||
// tools; tracking segments separately lets us exclude that preamble from the
|
||||
// persisted assistant message instead of leaking it into the final answer.
|
||||
type answerSegment struct {
|
||||
id string
|
||||
content string
|
||||
superseded bool
|
||||
}
|
||||
|
||||
// findAnswerSegment returns the segment for an answer event ID, or nil.
|
||||
// Callers must hold h.mu.
|
||||
func (h *AgentStreamHandler) findAnswerSegment(id string) *answerSegment {
|
||||
for _, seg := range h.answerSegments {
|
||||
if seg.id == id {
|
||||
return seg
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// composeFinalAnswer rebuilds the persisted answer from all non-superseded
|
||||
// segments in arrival order. Callers must hold h.mu.
|
||||
func (h *AgentStreamHandler) composeFinalAnswer() string {
|
||||
var b strings.Builder
|
||||
for _, seg := range h.answerSegments {
|
||||
if !seg.superseded {
|
||||
b.WriteString(seg.content)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// NewAgentStreamHandler creates a new handler for agent SSE streaming
|
||||
func NewAgentStreamHandler(
|
||||
ctx context.Context,
|
||||
@@ -133,6 +169,20 @@ func (h *AgentStreamHandler) handleToolCall(ctx context.Context, evt event.Event
|
||||
h.mu.Lock()
|
||||
// Track start time for this tool call (use tool_call_id as key)
|
||||
h.eventStartTimes[data.ToolCallID] = time.Now()
|
||||
// Any answer text streamed before this tool call was a non-terminal round's
|
||||
// preamble, not the final answer (the agent only ends by stopping naturally
|
||||
// with plain text and no tool calls). Drop those segments from the persisted
|
||||
// answer so the preamble never leaks into Message.Content.
|
||||
supersededAny := false
|
||||
for _, seg := range h.answerSegments {
|
||||
if !seg.superseded && seg.content != "" {
|
||||
seg.superseded = true
|
||||
supersededAny = true
|
||||
}
|
||||
}
|
||||
if supersededAny {
|
||||
h.finalAnswer = h.composeFinalAnswer()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
metadata := map[string]interface{}{
|
||||
@@ -346,6 +396,7 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
|
||||
// Track start time on first chunk
|
||||
if _, exists := h.eventStartTimes[evt.ID]; !exists {
|
||||
h.eventStartTimes[evt.ID] = time.Now()
|
||||
@@ -362,8 +413,17 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
|
||||
h.requestID, h.sessionID, ttfb.Milliseconds())
|
||||
}
|
||||
|
||||
// Accumulate final answer locally for assistant message (database)
|
||||
h.finalAnswer += data.Content
|
||||
// Accumulate final answer locally for assistant message (database). Track
|
||||
// per event ID so a later supersede can subtract this segment's content.
|
||||
if data.Content != "" {
|
||||
seg := h.findAnswerSegment(evt.ID)
|
||||
if seg == nil {
|
||||
seg = &answerSegment{id: evt.ID}
|
||||
h.answerSegments = append(h.answerSegments, seg)
|
||||
}
|
||||
seg.content += data.Content
|
||||
h.finalAnswer = h.composeFinalAnswer()
|
||||
}
|
||||
if data.IsFallback {
|
||||
h.assistantMessage.IsFallback = true
|
||||
}
|
||||
|
||||
@@ -1664,7 +1664,6 @@ var toolDisplayNames = map[string]string{
|
||||
"web_fetch": "网页阅读",
|
||||
"read_skill": "读取技能",
|
||||
"execute_skill_script": "执行技能脚本",
|
||||
"final_answer": "生成回答",
|
||||
}
|
||||
|
||||
// internalToolNames lists tools whose execution should NOT be displayed in IM
|
||||
@@ -1684,12 +1683,9 @@ func friendlyToolName(toolName string) string {
|
||||
}
|
||||
|
||||
// isToolVisibleToUser returns true if the tool's execution progress should be
|
||||
// displayed to the IM user. Internal reasoning tools (thinking, planning) and
|
||||
// the final_answer pseudo-tool are hidden.
|
||||
// displayed to the IM user. Internal reasoning tools (thinking, planning) are
|
||||
// hidden.
|
||||
func isToolVisibleToUser(toolName string) bool {
|
||||
if toolName == "final_answer" {
|
||||
return false
|
||||
}
|
||||
return !internalToolNames[toolName]
|
||||
}
|
||||
|
||||
|
||||
@@ -229,12 +229,12 @@ func (c *OllamaChat) ChatStream(
|
||||
}
|
||||
|
||||
// Ollama returns tool calls as complete objects (not incremental deltas).
|
||||
// Log this so we can trace non-streaming answer delivery.
|
||||
// Log this so we can trace non-streaming thought delivery.
|
||||
for _, tc := range resp.Message.ToolCalls {
|
||||
if tc.Function.Name == "final_answer" || tc.Function.Name == "thinking" {
|
||||
if tc.Function.Name == "thinking" {
|
||||
argsBytes, _ := json.Marshal(tc.Function.Arguments)
|
||||
logger.Warnf(ctx, "[Ollama Stream] Tool %q arrived non-incrementally (%d bytes args), "+
|
||||
"answer will not be token-streamed to frontend",
|
||||
"thought will not be token-streamed to frontend",
|
||||
tc.Function.Name, len(argsBytes))
|
||||
}
|
||||
}
|
||||
@@ -242,17 +242,6 @@ func (c *OllamaChat) ChatStream(
|
||||
for _, tc := range resp.Message.ToolCalls {
|
||||
argsMap := tc.Function.Arguments.ToMap()
|
||||
switch tc.Function.Name {
|
||||
case "final_answer":
|
||||
if answer, ok := argsMap["answer"].(string); ok && answer != "" {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: answer,
|
||||
Done: false,
|
||||
Data: map[string]interface{}{
|
||||
"source": "final_answer_tool",
|
||||
},
|
||||
}
|
||||
}
|
||||
case "thinking":
|
||||
if thought, ok := argsMap["thought"].(string); ok && thought != "" {
|
||||
streamChan <- types.StreamResponse{
|
||||
|
||||
@@ -583,6 +583,11 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context, messages []Message, opts
|
||||
}
|
||||
c.logRequest(timeoutCtx, req, true)
|
||||
|
||||
streamDumper := newStreamPacketDumper(c.modelName, req)
|
||||
if streamDumper != nil {
|
||||
logger.Infof(timeoutCtx, "[LLM Stream Raw Dump] writing packets to %s", streamDumper.Path())
|
||||
}
|
||||
|
||||
streamChan := make(chan types.StreamResponse)
|
||||
|
||||
stream, err := c.client.CreateChatCompletionStream(timeoutCtx, req)
|
||||
@@ -602,7 +607,10 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context, messages []Message, opts
|
||||
|
||||
go func() {
|
||||
defer cancel()
|
||||
c.processStream(timeoutCtx, stream, streamChan)
|
||||
if streamDumper != nil {
|
||||
defer streamDumper.Close()
|
||||
}
|
||||
c.processStream(timeoutCtx, stream, streamChan, streamDumper)
|
||||
}()
|
||||
|
||||
return streamChan, nil
|
||||
@@ -679,14 +687,23 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint stri
|
||||
}
|
||||
|
||||
streamChan := make(chan types.StreamResponse)
|
||||
streamDumper := newStreamPacketDumper(c.modelName, customReq)
|
||||
if streamDumper != nil {
|
||||
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", streamDumper.Path())
|
||||
}
|
||||
|
||||
go c.processRawHTTPStream(ctx, resp, streamChan)
|
||||
go func() {
|
||||
if streamDumper != nil {
|
||||
defer streamDumper.Close()
|
||||
}
|
||||
c.processRawHTTPStream(ctx, resp, streamChan, streamDumper)
|
||||
}()
|
||||
|
||||
return streamChan, nil
|
||||
}
|
||||
|
||||
// processStream 处理 OpenAI SDK 流式响应
|
||||
func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCompletionStream, streamChan chan types.StreamResponse) {
|
||||
func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCompletionStream, streamChan chan types.StreamResponse, dumper *streamPacketDumper) {
|
||||
defer close(streamChan)
|
||||
defer stream.Close()
|
||||
|
||||
@@ -719,6 +736,10 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
|
||||
return
|
||||
}
|
||||
|
||||
if dumper != nil {
|
||||
dumper.WritePacket(response)
|
||||
}
|
||||
|
||||
if response.Usage != nil {
|
||||
state.usage = &types.TokenUsage{
|
||||
PromptTokens: response.Usage.PromptTokens,
|
||||
@@ -735,7 +756,7 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
|
||||
}
|
||||
|
||||
// processRawHTTPStream 处理原始 HTTP 流式响应
|
||||
func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Response, streamChan chan types.StreamResponse) {
|
||||
func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Response, streamChan chan types.StreamResponse, dumper *streamPacketDumper) {
|
||||
defer close(streamChan)
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -793,6 +814,13 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
|
||||
continue
|
||||
}
|
||||
|
||||
if dumper != nil {
|
||||
// 保留上游 SSE data 行的原始 JSON,不经过中间结构体裁剪。
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
|
||||
// 使用局部结构体进行一次性解析,同时捕捉标准字段和 vLLM 的 reasoning 字段,避免性能损失
|
||||
var streamResp struct {
|
||||
openai.ChatCompletionStreamResponse
|
||||
@@ -1099,32 +1127,6 @@ func (c *RemoteAPIChat) processToolCallsDelta(ctx context.Context, toolCalls []o
|
||||
|
||||
state.lastFunctionName[toolCallIndex] = currName
|
||||
|
||||
// Stream final_answer tool arguments as answer-type chunks
|
||||
if toolCallEntry.Function.Name == "final_answer" && argsUpdated {
|
||||
extractor, exists := state.fieldExtractors[toolCallIndex]
|
||||
if !exists {
|
||||
extractor = newJSONFieldExtractor("answer")
|
||||
state.fieldExtractors[toolCallIndex] = extractor
|
||||
// Detect non-incremental arrival: if the first args chunk is large,
|
||||
// the model likely returned all arguments at once (non-streaming tool call)
|
||||
if len(tc.Function.Arguments) > 200 {
|
||||
logger.Warnf(ctx, "[LLM Stream] final_answer args arrived in large chunk (%d bytes), "+
|
||||
"model may not support incremental tool call streaming", len(tc.Function.Arguments))
|
||||
}
|
||||
}
|
||||
answerChunk := extractor.Feed(tc.Function.Arguments)
|
||||
if answerChunk != "" {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: answerChunk,
|
||||
Done: false,
|
||||
Data: map[string]interface{}{
|
||||
"source": "final_answer_tool",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stream thinking tool's thought field as thinking-type chunks
|
||||
if toolCallEntry.Function.Name == "thinking" && argsUpdated {
|
||||
extractor, exists := state.fieldExtractors[toolCallIndex]
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// streamRawDumpDir returns the directory for per-stream raw packet dumps.
|
||||
// Enabled when WEKNORA_LLM_STREAM_RAW_DUMP_DIR is set, or when
|
||||
// WEKNORA_LLM_STREAM_RAW_DUMP=1 (defaults to ~/.weknora/investigate/llm-stream).
|
||||
func streamRawDumpDir() string {
|
||||
if dir := strings.TrimSpace(os.Getenv("WEKNORA_LLM_STREAM_RAW_DUMP_DIR")); dir != "" {
|
||||
return dir
|
||||
}
|
||||
v := strings.TrimSpace(os.Getenv("WEKNORA_LLM_STREAM_RAW_DUMP"))
|
||||
if v == "1" || strings.EqualFold(v, "true") || strings.EqualFold(v, "yes") {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".weknora", "investigate", "llm-stream")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// streamPacketDumper writes one stream session to a dedicated JSONL file:
|
||||
// line 1 = request wrapper; following lines = raw provider chunk JSON.
|
||||
type streamPacketDumper struct {
|
||||
mu sync.Mutex
|
||||
file *os.File
|
||||
path string
|
||||
model string
|
||||
seq int
|
||||
}
|
||||
|
||||
func newStreamPacketDumper(modelName string, request any) *streamPacketDumper {
|
||||
dir := streamRawDumpDir()
|
||||
if dir == "" {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
safeModel := strings.Map(func(r rune) rune {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_', r == '.':
|
||||
return r
|
||||
default:
|
||||
return '_'
|
||||
}
|
||||
}, modelName)
|
||||
if safeModel == "" {
|
||||
safeModel = "model"
|
||||
}
|
||||
|
||||
name := fmt.Sprintf("llm_stream_%s_%s.jsonl", safeModel, time.Now().Format("20060102T150405.000000000"))
|
||||
path := filepath.Join(dir, name)
|
||||
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
d := &streamPacketDumper{file: f, path: path, model: modelName}
|
||||
_ = d.writeRequest(request)
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) writeRequest(request any) error {
|
||||
line, err := json.Marshal(map[string]any{
|
||||
"type": "request",
|
||||
"model": d.model,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"data": request,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.writeLine(line)
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) writeLine(line []byte) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if _, err := d.file.Write(line); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := d.file.Write([]byte{'\n'})
|
||||
return err
|
||||
}
|
||||
|
||||
// WritePacketRaw appends one provider chunk as a single JSONL line (valid JSON written as-is).
|
||||
func (d *streamPacketDumper) WritePacketRaw(raw []byte) {
|
||||
if d == nil || d.file == nil || len(raw) == 0 {
|
||||
return
|
||||
}
|
||||
raw = bytesTrimSpace(raw)
|
||||
if len(raw) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
d.seq++
|
||||
|
||||
if json.Valid(raw) {
|
||||
_, _ = d.file.Write(raw)
|
||||
_, _ = d.file.Write([]byte{'\n'})
|
||||
return
|
||||
}
|
||||
|
||||
line, _ := json.Marshal(map[string]any{
|
||||
"type": "packet",
|
||||
"seq": d.seq,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"data_raw": string(raw),
|
||||
})
|
||||
_, _ = d.file.Write(line)
|
||||
_, _ = d.file.Write([]byte{'\n'})
|
||||
}
|
||||
|
||||
// WritePacket marshals v as one JSON object per line (SDK stream Recv path).
|
||||
func (d *streamPacketDumper) WritePacket(v any) {
|
||||
if d == nil || v == nil {
|
||||
return
|
||||
}
|
||||
line, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
d.WritePacketRaw(line)
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) Path() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
return d.path
|
||||
}
|
||||
|
||||
func (d *streamPacketDumper) Close() {
|
||||
if d == nil || d.file == nil {
|
||||
return
|
||||
}
|
||||
_ = d.file.Close()
|
||||
d.file = nil
|
||||
}
|
||||
|
||||
func bytesTrimSpace(b []byte) []byte {
|
||||
return []byte(strings.TrimSpace(string(b)))
|
||||
}
|
||||
@@ -57,8 +57,8 @@ type ChatResponse struct {
|
||||
|
||||
// AnswerStreamed reports whether the user-facing answer text was already
|
||||
// streamed live to the final-answer UI area during this round (i.e. the
|
||||
// model answered with plain content rather than via the final_answer
|
||||
// tool). When true, the natural-stop branch must only emit the closing
|
||||
// model answered with plain content). When true, the natural-stop branch
|
||||
// must only emit the closing
|
||||
// Done marker for AnswerEventID instead of re-emitting the whole answer —
|
||||
// otherwise the answer would render twice and "jump" at end of stream.
|
||||
// Transient, never persisted.
|
||||
|
||||
Reference in New Issue
Block a user