Skip to content

Commit 78f07b0

Browse files
committed
fix: only count assistant messages when limiting consecutive tool calls
Before this change, the number of consecutive tool calls was counted by looking at all messages since the last time a message with role "user" was sent. This was bad logic because the LLM could ask for many parallel tool calls. This change addresses this problem by only considering messages with role "assistant" with tool calls since the last user message. Signed-off-by: Donnie Adams <[email protected]>
1 parent a89c442 commit 78f07b0

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

pkg/engine/engine.go

+11-4
Original file line numberDiff line numberDiff line change
@@ -400,17 +400,24 @@ func (e *Engine) complete(ctx context.Context, state *State) (*Return, error) {
400400
}
401401
}()
402402

403-
// Limit the number of consecutive tool calls and responses.
403+
// Limit the number of consecutive tool calls.
404404
// We don't want the LLM to call tools unrestricted or get stuck in an error loop.
405405
var messagesSinceLastUserMessage int
406406
for _, msg := range slices.Backward(state.Completion.Messages) {
407407
if msg.Role == types.CompletionMessageRoleTypeUser {
408408
break
409+
} else if msg.Role == types.CompletionMessageRoleTypeAssistant {
410+
for _, content := range msg.Content {
411+
// If this message is requesting that a tool call be made, then count it towards the limit.
412+
if content.ToolCall != nil {
413+
messagesSinceLastUserMessage++
414+
break
415+
}
416+
}
409417
}
410-
messagesSinceLastUserMessage++
411418
}
412-
// Divide by 2 because tool calls come in pairs: call and response.
413-
if messagesSinceLastUserMessage/2 > maxConsecutiveToolCalls {
419+
420+
if messagesSinceLastUserMessage > maxConsecutiveToolCalls {
414421
msg := fmt.Sprintf("We cannot continue because the number of consecutive tool calls is limited to %d.", maxConsecutiveToolCalls)
415422
ret.State.Completion.Messages = append(state.Completion.Messages, types.CompletionMessage{
416423
Role: types.CompletionMessageRoleTypeAssistant,

0 commit comments

Comments
 (0)