Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions loop/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -528,6 +529,42 @@ func TestInsertMissingToolResults(t *testing.T) {
}
}

// Synthetic results are rebuilt on every request and never stored, so they
// must come out in the same order each time; otherwise the request bytes
// change and the prompt cache misses from the interrupted turn onward.
func TestInsertMissingToolResultsIsDeterministic(t *testing.T) {
ids := []string{"tool_1", "tool_2", "tool_3", "tool_4", "tool_5", "tool_6"}
assistant := llm.Message{Role: llm.MessageRoleAssistant}
for _, id := range ids {
assistant.Content = append(assistant.Content, llm.Content{Type: llm.ContentTypeToolUse, ID: id, ToolName: "bash"})
}
answered := llm.Content{Type: llm.ContentTypeToolResult, ToolUseID: "tool_3"}
user := llm.Message{Role: llm.MessageRoleUser, Content: []llm.Content{answered, {Type: llm.ContentTypeText, Text: "stop"}}}

want := []string{"tool_1", "tool_2", "tool_4", "tool_5", "tool_6", "tool_3"}
for range 50 {
req := &llm.Request{Messages: []llm.Message{assistant, user}}
(&RunConfig{Logger: slog.Default()}).insertMissingToolResults(req)
var got []string
for _, c := range req.Messages[1].Content {
if c.Type == llm.ContentTypeToolResult {
got = append(got, c.ToolUseID)
}
}
if !slices.Equal(got, want) {
t.Fatalf("tool_result order = %v, want %v", got, want)
}
}

// A repeated tool_use ID still gets a single synthetic result.
assistant.Content = append(assistant.Content, assistant.Content[0])
req := &llm.Request{Messages: []llm.Message{assistant, user}}
(&RunConfig{Logger: slog.Default()}).insertMissingToolResults(req)
if n := len(req.Messages[1].Content); n != len(want)+1 {
t.Fatalf("got %d content items with a repeated tool_use ID, want %d", n, len(want)+1)
}
}

func TestInsertMissingToolResultsWithEdgeCases(t *testing.T) {
// Test for the bug: when an assistant error message is recorded after a tool_use
// but before tool execution, the tool_use is "hidden" from insertMissingToolResults
Expand Down
12 changes: 9 additions & 3 deletions loop/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -963,8 +963,11 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) {
totalInserted := 0
totalRemoved := 0

// Track the tool_use IDs from the most recent assistant message
// Track the tool_use IDs from the most recent assistant message, and their
// order: synthetic results must come out the same way on every request, or
// the prompt cache misses from this point on.
var prevAssistantToolUseIDs map[string]bool
var prevAssistantToolUseOrder []string

for i := 0; i < len(req.Messages); i++ {
msg := req.Messages[i]
Expand All @@ -982,9 +985,11 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) {

// Track all tool_use IDs in this assistant message
prevAssistantToolUseIDs = make(map[string]bool)
prevAssistantToolUseOrder = nil
for _, c := range msg.Content {
if c.Type == llm.ContentTypeToolUse {
if c.Type == llm.ContentTypeToolUse && !prevAssistantToolUseIDs[c.ID] {
prevAssistantToolUseIDs[c.ID] = true
prevAssistantToolUseOrder = append(prevAssistantToolUseOrder, c.ID)
}
}
newMessages = append(newMessages, msg)
Expand Down Expand Up @@ -1054,7 +1059,7 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) {
// Check if we need to add missing tool_results for this user message
if prevAssistantToolUseIDs != nil {
var prefix []llm.Content
for toolUseID := range prevAssistantToolUseIDs {
for _, toolUseID := range prevAssistantToolUseOrder {
if !existingResultIDs[toolUseID] {
prefix = append(prefix, llm.Content{
Type: llm.ContentTypeToolResult,
Expand Down Expand Up @@ -1084,6 +1089,7 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) {

// Reset for next iteration - user message "consumes" the previous tool_uses
prevAssistantToolUseIDs = nil
prevAssistantToolUseOrder = nil
} else {
newMessages = append(newMessages, msg)
}
Expand Down