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
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
+31
View File
@@ -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))
}
+9
View File
@@ -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 {
+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 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{
+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 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 {
+21 -2
View File
@@ -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