feat: preserve and echo thinking blocks for extended-thinking models (DeepSeek, Claude thinking mode)

This commit is contained in:
sausheong committed 2026-07-12 20:30:48 +08:00
1 parent d3c74e5681
commit 152d8b972e
6 files changed
+116 -17

No files matched your search

+25 -11
View File
@@ -17,6 +17,9 @@ const (
EventToolCallDone EventToolCallDone
EventDone EventDone
EventError 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. // ImageContent holds image data for multimodal messages.
@@ -26,13 +29,23 @@ type ImageContent struct {
} }
// Message represents a conversation message. // 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 { type Message struct {
Role string `json:"role"` // "user", "assistant", "system" Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
Images []ImageContent `json:"-"` // image attachments (not serialized) Images []ImageContent `json:"-"` // image attachments (not serialized)
ToolCalls []ToolCall `json:"tool_calls,omitempty"` ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
IsError bool `json:"is_error,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. // 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. // ChatEvent is a single streaming event from the LLM.
type ChatEvent struct { type ChatEvent struct {
Type EventType Type EventType
Text string Text string
ToolCall *ToolCall ToolCall *ToolCall
Usage *Usage ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
Error error Usage *Usage
Error error
// StopReason carries the provider's terminal stop reason on EventDone // StopReason carries the provider's terminal stop reason on EventDone
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when // ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
// the provider doesn't report one. StopReasonRefusal is the value the // the provider doesn't report one. StopReasonRefusal is the value the
+31
View File
@@ -171,6 +171,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
var pendingTools []pendingTC var pendingTools []pendingTC
var currentBlockType string var currentBlockType string
var inputTokens, cacheCreationTokens, cacheReadTokens int64 var inputTokens, cacheCreationTokens, cacheReadTokens int64
var pendingThinking strings.Builder
var pendingThinkingSignature string
for stream.Next() { for stream.Next() {
event := stream.Current() event := stream.Current()
@@ -187,6 +189,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
switch cb.Type { switch cb.Type {
case "text": case "text":
currentBlockType = "text" currentBlockType = "text"
case "thinking":
currentBlockType = "thinking"
pendingThinking.Reset()
pendingThinkingSignature = ""
case "tool_use": case "tool_use":
currentBlockType = "tool_use" currentBlockType = "tool_use"
pending := pendingTC{ pending := pendingTC{
@@ -219,6 +225,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
Type: llm.EventTextDelta, Type: llm.EventTextDelta,
Text: delta.Text, Text: delta.Text,
} }
case "thinking_delta":
pendingThinking.WriteString(delta.Thinking)
case "signature_delta":
pendingThinkingSignature += delta.Signature
case "input_json_delta": case "input_json_delta":
if len(pendingTools) > 0 { if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON) 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": 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 { if currentBlockType == "tool_use" && len(pendingTools) > 0 {
// Index in place rather than copying the element: the // Index in place rather than copying the element: the
// pendingTC holds a strings.Builder, which must not be // pendingTC holds a strings.Builder, which must not be
@@ -513,6 +534,16 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
} }
case "assistant": case "assistant":
var blocks []anthropic.ContentBlockParamUnion 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 != "" { if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content)) blocks = append(blocks, anthropic.NewTextBlock(m.Content))
} }
+9
View File
@@ -212,6 +212,15 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
Role: entry.Role, Role: entry.Role,
Content: md.Text, 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 // Convert session images to LLM image content
if entry.Role == "user" { if entry.Role == "user" {
for _, img := range md.Images { for _, img := range md.Images {
+16 -2
View File
@@ -531,6 +531,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
var textContent strings.Builder var textContent strings.Builder
var toolCalls []llm.ToolCall var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
gotFirstToken := false gotFirstToken := false
streamingOn := r.streamingToolsEnabled() 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}) 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: case llm.EventToolCallDone:
if event.ToolCall == nil { if event.ToolCall == nil {
continue continue
@@ -696,8 +705,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
"text_chars", textContent.Len(), "text_chars", textContent.Len(),
"tool_calls", len(toolCalls)) "tool_calls", len(toolCalls))
if textContent.Len() > 0 { if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String())) 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 { if r.KG != nil {
r.kgMu.Lock() r.kgMu.Lock()
thread = append(thread, Message{ thread = append(thread, Message{
+14 -2
View File
@@ -112,6 +112,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
var textContent strings.Builder var textContent strings.Builder
var toolCalls []llm.ToolCall var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
var lastUsage *llm.Usage var lastUsage *llm.Usage
retriedRefusal := false retriedRefusal := false
streamLoop: streamLoop:
@@ -125,6 +126,13 @@ streamLoop:
emit(AgentEvent{Type: EventTextDelta, Text: event.Text}) emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
case llm.EventToolCallStart: case llm.EventToolCallStart:
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall}) 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: case llm.EventToolCallDone:
if event.ToolCall != nil { if event.ToolCall != nil {
toolCalls = append(toolCalls, *event.ToolCall) toolCalls = append(toolCalls, *event.ToolCall)
@@ -170,8 +178,12 @@ streamLoop:
break streamLoop break streamLoop
} }
if textContent.Len() > 0 { if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String())) if len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
} else {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
} }
if len(toolCalls) == 0 { if len(toolCalls) == 0 {
+21 -2
View File
@@ -36,10 +36,18 @@ type ImageData struct {
Data string `json:"data"` // base64-encoded 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. // MessageData holds text message content.
type MessageData struct { type MessageData struct {
Text string `json:"text"` Text string `json:"text"`
Images []ImageData `json:"images,omitempty"` Images []ImageData `json:"images,omitempty"`
ThinkingBlocks []ThinkingBlockData `json:"thinking_blocks,omitempty"`
} }
// ToolCallData holds a tool call's details. // 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. // ToolCallEntry creates a tool call entry.
// //
// input is sanitised to "{}" when empty or not valid JSON. The // input is sanitised to "{}" when empty or not valid JSON. The