Skip to content

Commit a89c442

Browse files
committed
enhance: add a maximum consecutive tools calls restriction
This is a safety net for instances when the LLM goes awry. There is an undocumented environment variable to change the maximum number of consecutive tool calls from the default of 10. Signed-off-by: Donnie Adams <[email protected]>
1 parent 59ad4c0 commit a89c442

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

pkg/engine/engine.go

+35
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import (
44
"context"
55
"encoding/json"
66
"fmt"
7+
"os"
8+
"slices"
9+
"strconv"
710
"strings"
811
"sync"
912

@@ -12,6 +15,16 @@ import (
1215
"github.com/gptscript-ai/gptscript/pkg/version"
1316
)
1417

18+
var maxConsecutiveToolCalls = 10
19+
20+
func init() {
21+
if val := os.Getenv("GPTSCRIPT_MAX_CONSECUTIVE_TOOL_CALLS"); val != "" {
22+
if i, err := strconv.Atoi(val); err == nil && i > 0 {
23+
maxConsecutiveToolCalls = i
24+
}
25+
}
26+
}
27+
1528
type Model interface {
1629
Call(ctx context.Context, messageRequest types.CompletionRequest, env []string, status chan<- types.CompletionStatus) (*types.CompletionMessage, error)
1730
ProxyInfo([]string) (string, string, error)
@@ -387,6 +400,28 @@ func (e *Engine) complete(ctx context.Context, state *State) (*Return, error) {
387400
}
388401
}()
389402

403+
// Limit the number of consecutive tool calls and responses.
404+
// We don't want the LLM to call tools unrestricted or get stuck in an error loop.
405+
var messagesSinceLastUserMessage int
406+
for _, msg := range slices.Backward(state.Completion.Messages) {
407+
if msg.Role == types.CompletionMessageRoleTypeUser {
408+
break
409+
}
410+
messagesSinceLastUserMessage++
411+
}
412+
// Divide by 2 because tool calls come in pairs: call and response.
413+
if messagesSinceLastUserMessage/2 > maxConsecutiveToolCalls {
414+
msg := fmt.Sprintf("We cannot continue because the number of consecutive tool calls is limited to %d.", maxConsecutiveToolCalls)
415+
ret.State.Completion.Messages = append(state.Completion.Messages, types.CompletionMessage{
416+
Role: types.CompletionMessageRoleTypeAssistant,
417+
Content: []types.ContentPart{{Text: msg}},
418+
})
419+
// Setting this ensures that chat continues as expected when we hit this problem.
420+
state.Pending = map[string]types.CompletionToolCall{}
421+
ret.Result = &msg
422+
return &ret, nil
423+
}
424+
390425
resp, err := e.Model.Call(ctx, state.Completion, e.Env, progress)
391426
if err != nil {
392427
return nil, fmt.Errorf("failed calling model for completion: %w", err)

0 commit comments

Comments
 (0)