feat(im): align agent stream display with web thinking and tool progress

Mirror Web AgentStreamDisplay/RagPipelineProgress in IM text streams:
retract live answers into 思考过程, show Web-aligned tool titles with
query/summary from structured data, and collapse thinking on finalize
instead of dropping it entirely.
This commit is contained in:
wizardchen
2026-06-23 23:33:19 +08:00
committed by lyingbug
parent ab3e472748
commit c3b036cb00
16 changed files with 2001 additions and 279 deletions
+210 -1
View File
@@ -1,6 +1,215 @@
package im
import "strings"
import (
"fmt"
"regexp"
"strings"
)
// StreamDisplayPhase controls how raw IM stream content is rendered.
type StreamDisplayPhase int
const (
// StreamDisplayIntermediate shows in-progress thinking/tools (Web: expanded progress).
StreamDisplayIntermediate StreamDisplayPhase = iota
// StreamDisplayFinal shows answer-only text (Web: collapsed/hidden intermediate steps).
StreamDisplayFinal
)
var (
thinkBlockRe = regexp.MustCompile(`(?s)<think>.*?</think>`)
thinkOpenTailRe = regexp.MustCompile(`(?s)<think>.*$`)
)
// ragPipelineToolNames mirrors frontend RAG_PIPELINE_TOOL_NAMES.
var ragPipelineToolNames = map[string]bool{
"query_understand": true,
"knowledge_search": true,
}
// IsRAGPipelineToolName reports whether a tool is part of the quick-QA progress UI.
func IsRAGPipelineToolName(name string) bool {
return ragPipelineToolNames[name]
}
// StripThinkBlocks removes <think> blocks for final IM display.
func StripThinkBlocks(content string) string {
if content == "" {
return ""
}
cleaned := thinkBlockRe.ReplaceAllString(content, "")
cleaned = thinkOpenTailRe.ReplaceAllString(cleaned, "")
return trimIMOuterWhitespace(cleaned)
}
// IMStreamMode distinguishes agent reasoning from quick-QA RAG pipeline display.
type IMStreamMode int
const (
IMStreamModeAgent IMStreamMode = iota
IMStreamModeQuickQA
)
// IMStreamParts separates stream content for IM display.
type IMStreamParts struct {
Mode IMStreamMode
// Quick-QA (RagPipelineProgress on Web):
PipelineInner string // non-tool pipeline narrative (if any)
PipelineToolSteps []IMToolStep // query_understand / knowledge_search rows
ReasoningInner string // model reasoning_content — separate "思考" section
// Agent (AgentStreamDisplay on Web):
AgentInner string // retracted preambles + thoughts ("思考过程")
AgentToolSteps []IMToolStep // tool progress lines (one row per tool_call_id)
LiveAnswer string // optimistic answer stream before tools retract it
Answer string // final answer (complete / knowledge QA)
}
func agentThinkContent(parts IMStreamParts) string {
toolLines := renderIMToolSteps(parts.AgentToolSteps, FormatIMToolLine)
return mergeIMNarrativeAndTools(parts.AgentInner, toolLines)
}
func quickQAPipelineContent(parts IMStreamParts) string {
toolLines := renderIMToolSteps(parts.PipelineToolSteps, FormatIMRagPipelineLine)
return mergeIMNarrativeAndTools(parts.PipelineInner, toolLines)
}
// RAGThinkingStyle matches Web RagPipelineProgress thinking row (agent.think).
var RAGThinkingStyle = ThinkBlockStyle{
ThinkingHeader: "> 💭 **思考中...**\n",
ThoughtHeader: "> 💭 **思考**\n",
LinePrefix: "> ",
LineSuffix: "",
Separator: "\n---\n\n",
}
// WrapThinkBlock wraps inner content with think tags for formatting.
func WrapThinkBlock(inner string) string {
inner = strings.TrimSpace(inner)
if inner == "" {
return ""
}
return "<think>\n" + inner + "\n</think>"
}
// BuildIMAgentStreamRaw assembles agent-mode raw content.
func BuildIMAgentStreamRaw(parts IMStreamParts, agentInProgress bool) string {
thinkTagged := WrapThinkBlock(agentThinkContent(parts))
if agentInProgress || strings.TrimSpace(parts.Answer) == "" {
return thinkTagged
}
if thinkTagged == "" {
return parts.Answer
}
return thinkTagged + "\n\n" + parts.Answer
}
// formatIMAgentIntermediate mirrors Web AgentStreamDisplay:
// stream answer text first; when tools run, retract into "思考过程";
// once tools exist, keep the think block visible above the streaming answer.
func formatIMAgentIntermediate(parts IMStreamParts) string {
think := strings.TrimSpace(agentThinkContent(parts))
live := strings.TrimSpace(parts.LiveAnswer)
var sections []string
if think != "" {
sections = append(sections, FormatIMDisplayContent(WrapThinkBlock(think), StreamDisplayIntermediate))
}
if live != "" {
sections = append(sections, live)
}
return strings.Join(sections, MarkdownThinkStyle.Separator)
}
// buildIMAgentCollapsedSummary returns a one-line collapsed think header (Web: tree root).
func buildIMAgentCollapsedSummary(parts IMStreamParts) string {
think := strings.TrimSpace(agentThinkContent(parts))
if think == "" {
return ""
}
summary := formatIMAgentStepsSummary(parts)
line := "> 💭 **思考过程**"
if summary != "" {
line += " · " + summary
}
return line
}
func formatIMAgentStepsSummary(parts IMStreamParts) string {
toolCount := len(parts.AgentToolSteps)
hasNarrative := strings.TrimSpace(parts.AgentInner) != ""
var segments []string
if hasNarrative {
segments = append(segments, "思考 1 轮")
}
if toolCount > 0 {
segments = append(segments, fmt.Sprintf("调用 %d 次工具", toolCount))
}
if len(segments) == 0 {
return ""
}
return strings.Join(segments, " · ")
}
// formatIMQuickQAIntermediate mirrors Web RagPipelineProgress:
// pipeline steps as plain lines, model reasoning in a separate "思考" block,
// and once answer starts streaming the progress collapses to answer-only preview.
func formatIMQuickQAIntermediate(parts IMStreamParts) string {
if answer := strings.TrimSpace(parts.Answer); answer != "" {
return answer
}
var sections []string
if p := strings.TrimSpace(quickQAPipelineContent(parts)); p != "" {
sections = append(sections, p)
}
if r := strings.TrimSpace(parts.ReasoningInner); r != "" {
sections = append(sections, TransformThinkBlocks(WrapThinkBlock(r), RAGThinkingStyle))
}
return strings.Join(sections, "\n\n")
}
// FormatIMIntermediateFromParts formats in-progress IM stream display.
func FormatIMIntermediateFromParts(parts IMStreamParts, agentInProgress bool) string {
if parts.Mode == IMStreamModeQuickQA {
return formatIMQuickQAIntermediate(parts)
}
_ = agentInProgress
return formatIMAgentIntermediate(parts)
}
// FormatIMFinalFromParts returns the final replace frame: collapsed think summary + answer for agent mode.
func FormatIMFinalFromParts(parts IMStreamParts) string {
answer := strings.TrimSpace(parts.Answer)
if parts.Mode == IMStreamModeAgent {
if collapsed := buildIMAgentCollapsedSummary(parts); collapsed != "" && answer != "" {
return collapsed + MarkdownThinkStyle.Separator + answer
}
}
if answer != "" {
return answer
}
// Fallback for embedded think tags in non-agent answers.
return FormatIMDisplayContent(BuildIMAgentStreamRaw(parts, false), StreamDisplayFinal)
}
// FormatIMDisplayContent formats raw stream content for the given display phase.
func FormatIMDisplayContent(raw string, phase StreamDisplayPhase) string {
switch phase {
case StreamDisplayFinal:
return StripThinkBlocks(raw)
default:
return TransformThinkBlocks(raw, MarkdownThinkStyle)
}
}
func trimIMOuterWhitespace(s string) string {
return strings.TrimSpace(s)
}
// ThinkBlockStyle controls how <think>...</think> blocks are rendered.
type ThinkBlockStyle struct {