From 152d8b972ed7b579082dba585f77a7fe6d4c912b Mon Sep 17 00:00:00 2001 From: sausheong Date: Sun, 12 Jul 2026 20:30:48 +0800 Subject: [PATCH] feat: preserve and echo thinking blocks for extended-thinking models (DeepSeek, Claude thinking mode) --- llm/provider.go | 36 ++++++++++++++++++++++---------- providers/anthropic/anthropic.go | 31 +++++++++++++++++++++++++++ runtime/context.go | 9 ++++++++ runtime/runtime.go | 18 ++++++++++++++-- runtime/runturn.go | 16 ++++++++++++-- session/session.go | 23 ++++++++++++++++++-- 6 files changed, 116 insertions(+), 17 deletions(-) diff --git a/llm/provider.go b/llm/provider.go index f7133e7..398f4f0 100644 --- a/llm/provider.go +++ b/llm/provider.go @@ -17,6 +17,9 @@ const ( EventToolCallDone EventDone EventError + // EventThinkingBlock is emitted when the model returns an extended-thinking + // block. The runtime must echo these back in subsequent turns verbatim. + EventThinkingBlock ) // ImageContent holds image data for multimodal messages. @@ -26,13 +29,23 @@ type ImageContent struct { } // Message represents a conversation message. +// ThinkingBlock holds an opaque thinking/reasoning block returned by models +// that support extended thinking (e.g. Anthropic with thinking enabled, +// DeepSeek-v4-pro). The Signature field is the provider-supplied integrity +// token that must be echoed back verbatim in subsequent turns. +type ThinkingBlock struct { + Thinking string `json:"thinking"` + Signature string `json:"signature,omitempty"` +} + type Message struct { - Role string `json:"role"` // "user", "assistant", "system" - Content string `json:"content,omitempty"` - Images []ImageContent `json:"-"` // image attachments (not serialized) - ToolCalls []ToolCall `json:"tool_calls,omitempty"` - ToolCallID string `json:"tool_call_id,omitempty"` // for tool results - IsError bool `json:"is_error,omitempty"` // for tool results + Role string `json:"role"` // "user", "assistant", "system" + Content string `json:"content,omitempty"` + Images []ImageContent `json:"-"` // image attachments (not serialized) + ToolCalls []ToolCall `json:"tool_calls,omitempty"` + ToolCallID string `json:"tool_call_id,omitempty"` // for tool results + IsError bool `json:"is_error,omitempty"` // for tool results + ThinkingBlocks []ThinkingBlock `json:"thinking_blocks,omitempty"` // echoed back for thinking-mode models } // ToolCall represents a tool invocation requested by the LLM. @@ -130,11 +143,12 @@ type Usage struct { // ChatEvent is a single streaming event from the LLM. type ChatEvent struct { - Type EventType - Text string - ToolCall *ToolCall - Usage *Usage - Error error + Type EventType + Text string + ToolCall *ToolCall + ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock + Usage *Usage + Error error // StopReason carries the provider's terminal stop reason on EventDone // ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when // the provider doesn't report one. StopReasonRefusal is the value the diff --git a/providers/anthropic/anthropic.go b/providers/anthropic/anthropic.go index 0604505..9d9145b 100644 --- a/providers/anthropic/anthropic.go +++ b/providers/anthropic/anthropic.go @@ -171,6 +171,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) var pendingTools []pendingTC var currentBlockType string var inputTokens, cacheCreationTokens, cacheReadTokens int64 + var pendingThinking strings.Builder + var pendingThinkingSignature string for stream.Next() { event := stream.Current() @@ -187,6 +189,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) switch cb.Type { case "text": currentBlockType = "text" + case "thinking": + currentBlockType = "thinking" + pendingThinking.Reset() + pendingThinkingSignature = "" case "tool_use": currentBlockType = "tool_use" pending := pendingTC{ @@ -219,6 +225,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) Type: llm.EventTextDelta, Text: delta.Text, } + case "thinking_delta": + pendingThinking.WriteString(delta.Thinking) + case "signature_delta": + pendingThinkingSignature += delta.Signature case "input_json_delta": if len(pendingTools) > 0 { pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON) @@ -226,6 +236,17 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) } case "content_block_stop": + if currentBlockType == "thinking" { + events <- llm.ChatEvent{ + Type: llm.EventThinkingBlock, + ThinkingBlock: &llm.ThinkingBlock{ + Thinking: pendingThinking.String(), + Signature: pendingThinkingSignature, + }, + } + pendingThinking.Reset() + pendingThinkingSignature = "" + } if currentBlockType == "tool_use" && len(pendingTools) > 0 { // Index in place rather than copying the element: the // pendingTC holds a strings.Builder, which must not be @@ -513,6 +534,16 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag } case "assistant": var blocks []anthropic.ContentBlockParamUnion + // Thinking blocks must come first, before text and tool_use. + for _, tb := range m.ThinkingBlocks { + blocks = append(blocks, anthropic.ContentBlockParamUnion{ + OfThinking: &anthropic.ThinkingBlockParam{ + Type: "thinking", + Thinking: tb.Thinking, + Signature: tb.Signature, + }, + }) + } if m.Content != "" { blocks = append(blocks, anthropic.NewTextBlock(m.Content)) } diff --git a/runtime/context.go b/runtime/context.go index 14ac14e..8e4d499 100644 --- a/runtime/context.go +++ b/runtime/context.go @@ -212,6 +212,15 @@ func assembleMessages(history []session.SessionEntry) []llm.Message { Role: entry.Role, Content: md.Text, } + // Restore thinking blocks for assistant messages (must be echoed back). + if entry.Role == "assistant" { + for _, tb := range md.ThinkingBlocks { + msg.ThinkingBlocks = append(msg.ThinkingBlocks, llm.ThinkingBlock{ + Thinking: tb.Thinking, + Signature: tb.Signature, + }) + } + } // Convert session images to LLM image content if entry.Role == "user" { for _, img := range md.Images { diff --git a/runtime/runtime.go b/runtime/runtime.go index ea6fb6b..b76be17 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -531,6 +531,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon var textContent strings.Builder var toolCalls []llm.ToolCall + var thinkingBlocks []session.ThinkingBlockData gotFirstToken := false streamingOn := r.streamingToolsEnabled() @@ -562,6 +563,14 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon } r.emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall}) + case llm.EventThinkingBlock: + if event.ThinkingBlock != nil { + thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{ + Thinking: event.ThinkingBlock.Thinking, + Signature: event.ThinkingBlock.Signature, + }) + } + case llm.EventToolCallDone: if event.ToolCall == nil { continue @@ -696,8 +705,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon "text_chars", textContent.Len(), "tool_calls", len(toolCalls)) - if textContent.Len() > 0 { - r.Session.Append(session.AssistantMessageEntry(textContent.String())) + if textContent.Len() > 0 || len(thinkingBlocks) > 0 { + if len(thinkingBlocks) > 0 { + r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks)) + } else { + r.Session.Append(session.AssistantMessageEntry(textContent.String())) + } + thinkingBlocks = nil if r.KG != nil { r.kgMu.Lock() thread = append(thread, Message{ diff --git a/runtime/runturn.go b/runtime/runturn.go index 1271d49..c28b6d6 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -112,6 +112,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag var textContent strings.Builder var toolCalls []llm.ToolCall + var thinkingBlocks []session.ThinkingBlockData var lastUsage *llm.Usage retriedRefusal := false streamLoop: @@ -125,6 +126,13 @@ streamLoop: emit(AgentEvent{Type: EventTextDelta, Text: event.Text}) case llm.EventToolCallStart: emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall}) + case llm.EventThinkingBlock: + if event.ThinkingBlock != nil { + thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{ + Thinking: event.ThinkingBlock.Thinking, + Signature: event.ThinkingBlock.Signature, + }) + } case llm.EventToolCallDone: if event.ToolCall != nil { toolCalls = append(toolCalls, *event.ToolCall) @@ -170,8 +178,12 @@ streamLoop: break streamLoop } - if textContent.Len() > 0 { - r.Session.Append(session.AssistantMessageEntry(textContent.String())) + if textContent.Len() > 0 || len(thinkingBlocks) > 0 { + if len(thinkingBlocks) > 0 { + r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks)) + } else { + r.Session.Append(session.AssistantMessageEntry(textContent.String())) + } } if len(toolCalls) == 0 { diff --git a/session/session.go b/session/session.go index db2737c..3a544cf 100644 --- a/session/session.go +++ b/session/session.go @@ -36,10 +36,18 @@ type ImageData struct { Data string `json:"data"` // base64-encoded } +// ThinkingBlockData stores a thinking block from a model response. +// It must be echoed back verbatim in subsequent turns. +type ThinkingBlockData struct { + Thinking string `json:"thinking"` + Signature string `json:"signature,omitempty"` +} + // MessageData holds text message content. type MessageData struct { - Text string `json:"text"` - Images []ImageData `json:"images,omitempty"` + Text string `json:"text"` + Images []ImageData `json:"images,omitempty"` + ThinkingBlocks []ThinkingBlockData `json:"thinking_blocks,omitempty"` } // ToolCallData holds a tool call's details. @@ -338,6 +346,17 @@ func AssistantMessageEntry(text string) SessionEntry { } } +// AssistantMessageEntryWithThinking creates an assistant message entry that +// includes thinking blocks which must be echoed back in subsequent turns. +func AssistantMessageEntryWithThinking(text string, blocks []ThinkingBlockData) SessionEntry { + data, _ := json.Marshal(MessageData{Text: text, ThinkingBlocks: blocks}) + return SessionEntry{ + Type: EntryTypeMessage, + Role: "assistant", + Data: data, + } +} + // ToolCallEntry creates a tool call entry. // // input is sanitised to "{}" when empty or not valid JSON. The