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
+3 -14
View File
@@ -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{
+32 -30
View File
@@ -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]
+158
View File
@@ -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)))
}