Skip to content

Commit 955bc9c

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 e7b2e64 commit 955bc9c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

pkg/engine/engine.go

+33
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)
@@ -385,6 +398,26 @@ func (e *Engine) complete(ctx context.Context, state *State) (*Return, error) {
385398
}
386399
}()
387400

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

0 commit comments

Comments
 (0)