forked from mudler/cogito
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.go
More file actions
2049 lines (1784 loc) · 65 KB
/
Copy pathtools.go
File metadata and controls
2049 lines (1784 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cogito
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"github.com/google/uuid"
"github.com/mudler/cogito/prompt"
"github.com/mudler/xlog"
"github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/jsonschema"
)
var (
ErrNoToolSelected error = errors.New("no tool selected by the LLM")
ErrLoopDetected error = errors.New("loop detected: same tool called repeatedly with same parameters")
ErrToolCallCallbackInterrupted error = errors.New("interrupted via ToolCallCallback")
)
type ToolStatus struct {
Executed bool
ToolArguments ToolChoice
Result string
Name string
ResultData any
}
type SessionState struct {
ToolChoice *ToolChoice `json:"tool_choice"`
Fragment Fragment `json:"fragment"`
// AgentID identifies the sub-agent whose tool call is being evaluated.
// Empty for the root agent. Set when the tool-call callback is invoked
// from within a spawned sub-agent (see WithToolCallBack propagation).
AgentID string `json:"agent_id,omitempty"`
}
// decisionResult holds the result of a tool decision from the LLM
type decisionResult struct {
toolChoices []*ToolChoice
message string
reasoning string
usage LLMUsage
}
type ToolDefinitionInterface interface {
Tool() openai.Tool
// Execute runs the tool with the given arguments (as JSON map) and returns the result
Execute(args map[string]any) (string, any, error)
}
type Tool[T any] interface {
Run(args T) (string, any, error)
}
type ToolDefinition[T any] struct {
ToolRunner Tool[T]
InputArguments any
Name, Description string
}
func NewToolDefinition[T any](toolRunner Tool[T], inputArguments any, name, description string) ToolDefinitionInterface {
return &ToolDefinition[T]{
ToolRunner: toolRunner,
InputArguments: inputArguments,
Name: name,
Description: description,
}
}
var _ ToolDefinitionInterface = &ToolDefinition[any]{}
func (t ToolDefinition[T]) Tool() openai.Tool {
var schema *jsonschema.Definition
// Handle map[string]interface{} (JSON schema format)
if inputMap, ok := t.InputArguments.(map[string]any); ok {
dat, err := json.Marshal(inputMap)
if err != nil {
panic(err)
}
s := &jsonschema.Definition{}
err = json.Unmarshal(dat, s)
if err != nil {
panic(err)
}
schema = s
} else {
// Try to generate schema from struct type
var err error
schema, err = jsonschema.GenerateSchemaForType(t.InputArguments)
if err != nil {
panic(fmt.Errorf("unsupported InputArguments type: %T, error: %w", t.InputArguments, err))
}
}
return openai.Tool{
Type: openai.ToolTypeFunction,
Function: &openai.FunctionDefinition{
Name: t.Name,
Description: t.Description,
Parameters: *schema,
},
}
}
// Execute implements ToolDef.Execute by marshaling the arguments map to type T and calling ToolRunner.Run
func (t *ToolDefinition[T]) Execute(args map[string]any) (string, any, error) {
if t.ToolRunner == nil {
return "", nil, fmt.Errorf("tool %s has no ToolRunner", t.Name)
}
argsPtr := new(T)
// Marshal the map to JSON and unmarshal into the typed struct
argsBytes, err := json.Marshal(args)
if err != nil {
return "", nil, fmt.Errorf("failed to marshal tool arguments: %w", err)
}
err = json.Unmarshal(argsBytes, argsPtr)
if err != nil {
return "", nil, fmt.Errorf("failed to unmarshal tool arguments: %w", err)
}
// Call Run with the typed arguments
return t.ToolRunner.Run(*argsPtr)
}
type Tools []ToolDefinitionInterface
func (t Tools) Find(name string) ToolDefinitionInterface {
for _, tool := range t {
if tool.Tool().Function.Name == name {
return tool
}
}
return nil
}
func (t Tools) ToOpenAI() []openai.Tool {
openaiTools := []openai.Tool{}
for _, tool := range t {
openaiTools = append(openaiTools, tool.Tool())
}
return openaiTools
}
func (t Tools) Definitions() []*openai.FunctionDefinition {
defs := []*openai.FunctionDefinition{}
for _, tool := range t {
if tool.Tool().Function != nil {
defs = append(defs, tool.Tool().Function)
}
}
return defs
}
func (t Tools) Names() []string {
names := make([]string, len(t))
for i, tool := range t {
names[i] = tool.Tool().Function.Name
}
return names
}
// checkForLoop detects if the same tool with same parameters is being called repeatedly
func checkForLoop(pastActions []ToolStatus, currentTool *ToolChoice, loopDetectionSteps int) bool {
if loopDetectionSteps <= 0 || currentTool == nil {
return false
}
count := 0
for _, pastAction := range pastActions {
if pastAction.Name == currentTool.Name {
// Check if arguments are the same
// Simple comparison - could be enhanced with deep equality
if fmt.Sprintf("%v", pastAction.ToolArguments.Arguments) == fmt.Sprintf("%v", currentTool.Arguments) {
count++
}
}
}
return count >= loopDetectionSteps
}
// normalizeSystemMessages consolidates all system messages at the beginning of the
// conversation. Some models (e.g., Qwen) require system messages to appear only at
// the start of the conversation and will reject requests with mid-conversation system
// messages.
func normalizeSystemMessages(messages []openai.ChatCompletionMessage) []openai.ChatCompletionMessage {
if len(messages) == 0 {
return messages
}
// Check if normalization is needed: find system messages after position 0
needsNormalization := false
for i, msg := range messages {
if i > 0 && msg.Role == "system" {
needsNormalization = true
break
}
}
if !needsNormalization {
return messages
}
var systemParts []string
var nonSystem []openai.ChatCompletionMessage
for _, msg := range messages {
if msg.Role == "system" {
if msg.Content != "" {
systemParts = append(systemParts, msg.Content)
}
} else {
nonSystem = append(nonSystem, msg)
}
}
if len(systemParts) == 0 {
return nonSystem
}
result := make([]openai.ChatCompletionMessage, 0, len(nonSystem)+1)
result = append(result, openai.ChatCompletionMessage{
Role: "system",
Content: strings.Join(systemParts, "\n\n"),
})
result = append(result, nonSystem...)
return result
}
// mergeConsecutiveAssistantMessages collapses runs of two or more consecutive
// assistant messages into a single assistant message. Some chat backends
// (notably llama.cpp via LocalAI) reject a request whose message list ends with
// two or more assistant messages in a row, failing with
// "Cannot have 2 or more assistant messages at the end of the list".
//
// cogito's tool loop can legitimately append an assistant "reasoning" message
// on top of a fragment that already ends with an assistant message, so the
// conversation handed to a decision call must be normalized first. Merging
// preserves all content and tool calls while guaranteeing the list never ends
// with consecutive assistant messages.
func mergeConsecutiveAssistantMessages(messages []openai.ChatCompletionMessage) []openai.ChatCompletionMessage {
if len(messages) < 2 {
return messages
}
merged := make([]openai.ChatCompletionMessage, 0, len(messages))
for _, msg := range messages {
if len(merged) > 0 && msg.Role == "assistant" && merged[len(merged)-1].Role == "assistant" {
prev := &merged[len(merged)-1]
if msg.Content != "" {
if prev.Content != "" {
prev.Content += "\n\n"
}
prev.Content += msg.Content
}
prev.ToolCalls = append(prev.ToolCalls, msg.ToolCalls...)
continue
}
merged = append(merged, msg)
}
return merged
}
// decisionWithStreaming is like decision but uses streaming when a StreamingLLM and
// callback are available, forwarding reasoning/content/tool_call deltas live.
// Falls back to decision() when streaming is not possible.
func decisionWithStreaming(ctx context.Context, llm LLM, conversation []openai.ChatCompletionMessage,
tools Tools, forceTool string, maxRetries int, streamCB StreamCallback) (*decisionResult, error) {
sllm, isStreaming := llm.(StreamingLLM)
if !isStreaming || streamCB == nil {
return decision(ctx, llm, conversation, tools, forceTool, maxRetries)
}
req := openai.ChatCompletionRequest{
Messages: mergeConsecutiveAssistantMessages(normalizeSystemMessages(conversation)),
Tools: tools.ToOpenAI(),
}
if forceTool != "" {
req.ToolChoice = openai.ToolChoice{
Type: openai.ToolTypeFunction,
Function: openai.ToolFunction{Name: forceTool},
}
}
xlog.Debug("[decisionWithStreaming] available tools for selection", "tools", tools.Names())
var lastErr error
for attempts := 0; attempts < maxRetries; attempts++ {
// Abort promptly if the execution context was cancelled.
if err := ctx.Err(); err != nil {
return nil, err
}
ch, err := sllm.CreateChatCompletionStream(ctx, req)
if err != nil {
lastErr = err
xlog.Warn("Streaming attempt to make a decision failed", "attempt", attempts+1, "error", err)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
var contentBuf strings.Builder
var reasoningBuf strings.Builder
toolCallMap := make(map[int]*openai.ToolCall)
var toolCallOrder []int
var streamErr error
var usage LLMUsage
for ev := range ch {
streamCB(ev)
switch ev.Type {
case StreamEventContent:
contentBuf.WriteString(ev.Content)
case StreamEventReasoning:
reasoningBuf.WriteString(ev.Content)
case StreamEventToolCall:
idx := ev.ToolCallIndex
tc, exists := toolCallMap[idx]
if !exists {
tc = &openai.ToolCall{
Type: openai.ToolTypeFunction,
}
toolCallMap[idx] = tc
toolCallOrder = append(toolCallOrder, idx)
}
if ev.ToolCallID != "" {
tc.ID = ev.ToolCallID
}
if ev.ToolName != "" {
tc.Function.Name = ev.ToolName
}
tc.Function.Arguments += ev.ToolArgs
case StreamEventDone:
usage = ev.Usage
case StreamEventError:
streamErr = ev.Error
}
}
if streamErr != nil {
lastErr = streamErr
xlog.Warn("Streaming decision encountered error", "attempt", attempts+1, "error", streamErr)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
// Build tool calls slice in index order
var toolCalls []openai.ToolCall
for _, idx := range toolCallOrder {
toolCalls = append(toolCalls, *toolCallMap[idx])
}
reasoning := reasoningBuf.String()
content := contentBuf.String()
xlog.Debug("[decisionWithStreaming] processed", "message", content, "reasoning", reasoning)
if len(toolCalls) == 0 {
if content == "" {
// Model produced no visible content (empty response or only reasoning) — retry
xlog.Warn("Streaming decision produced no content, retrying", "attempt", attempts+1)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
return &decisionResult{message: content, reasoning: reasoning, usage: usage}, nil
}
// Process all tool calls
toolChoices := make([]*ToolChoice, 0, len(toolCalls))
allParsed := true
for _, toolCall := range toolCalls {
arguments := make(map[string]any)
if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &arguments); err != nil {
lastErr = err
xlog.Warn("Attempt to parse streamed tool arguments failed", "attempt", attempts+1, "error", err)
allParsed = false
break
}
toolChoices = append(toolChoices, &ToolChoice{
Name: toolCall.Function.Name,
Arguments: arguments,
})
}
if !allParsed {
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
xlog.Debug("[decisionWithStreaming] tools selected", "message", content, "toolChoices", len(toolChoices))
return &decisionResult{
toolChoices: toolChoices,
message: content,
reasoning: reasoning,
usage: usage,
}, nil
}
return nil, fmt.Errorf("failed to make a streaming decision after %d attempts: %w", maxRetries, lastErr)
}
// backoffOrCancel waits the retry backoff for the given attempt, returning the
// context error immediately if the context is cancelled during the wait. This
// keeps the decision retry loops responsive to cancellation: a cancelled call
// aborts at once instead of sleeping through the full backoff before retrying.
func backoffOrCancel(ctx context.Context, attempt int) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(attempt+1) * time.Second):
return nil
}
}
// decision forces the LLM to make a tool choice with retry logic
// Similar to agent.go's decision function but adapted for cogito's architecture
func decision(ctx context.Context, llm LLM, conversation []openai.ChatCompletionMessage,
tools Tools, forceTool string, maxRetries int) (*decisionResult, error) {
decision := openai.ChatCompletionRequest{
Messages: mergeConsecutiveAssistantMessages(normalizeSystemMessages(conversation)),
Tools: tools.ToOpenAI(),
}
if forceTool != "" {
decision.ToolChoice = openai.ToolChoice{
Type: openai.ToolTypeFunction,
Function: openai.ToolFunction{Name: forceTool},
}
}
xlog.Debug("[decision] available tools for selection", "tools", tools.Names())
var lastErr error
for attempts := 0; attempts < maxRetries; attempts++ {
// Abort promptly if the execution context was cancelled.
if err := ctx.Err(); err != nil {
return nil, err
}
resp, usage, err := llm.CreateChatCompletion(ctx, decision)
if err != nil {
lastErr = err
xlog.Warn("Attempt to make a decision failed", "attempt", attempts+1, "error", err)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
if len(resp.ChatCompletionResponse.Choices) != 1 {
lastErr = fmt.Errorf("no choices: %d", len(resp.ChatCompletionResponse.Choices))
xlog.Warn("Attempt to make a decision failed", "attempt", attempts+1, "error", lastErr)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
msg := resp.ChatCompletionResponse.Choices[0].Message
reasoning := resp.ReasoningContent
//reasoning := resp.Choices[0].Reasoning
xlog.Debug("[decision] processed", "message", msg.Content, "reasoning", reasoning)
if len(msg.ToolCalls) == 0 {
// No tool call - the LLM just responded with text
return &decisionResult{message: msg.Content, reasoning: reasoning, usage: usage}, nil
}
// Process all tool calls
toolChoices := make([]*ToolChoice, 0, len(msg.ToolCalls))
for _, toolCall := range msg.ToolCalls {
arguments := make(map[string]any)
if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &arguments); err != nil {
lastErr = err
xlog.Warn("Attempt to parse tool arguments failed", "attempt", attempts+1, "error", err)
if werr := backoffOrCancel(ctx, attempts); werr != nil {
return nil, werr
}
continue
}
toolChoices = append(toolChoices, &ToolChoice{
Name: toolCall.Function.Name,
Arguments: arguments,
})
}
xlog.Debug("[decision] tools selected", "message", msg.Content, "toolChoices", len(toolChoices))
// If we successfully parsed all tool calls, return the result
if len(toolChoices) == len(msg.ToolCalls) {
result := &decisionResult{
toolChoices: toolChoices,
message: msg.Content,
reasoning: reasoning,
usage: usage,
}
return result, nil
}
}
return nil, fmt.Errorf("failed to make a decision after %d attempts: %w", maxRetries, lastErr)
}
// formatToolParameters formats tool parameters for the prompt
func formatToolParameters(params interface{}) string {
// Convert parameters to JSON for inspection
paramsJSON, err := json.MarshalIndent(params, "", " ")
if err != nil {
return fmt.Sprintf("%v", params)
}
return string(paramsJSON)
}
// generateToolParameters generates parameters for a specific tool with enhanced reasoning
func generateToolParameters(o *Options, llm LLM, tool ToolDefinitionInterface, conversation []openai.ChatCompletionMessage,
reasoning string) (*ToolChoice, error) {
toolFunc := tool.Tool().Function
if toolFunc == nil {
return nil, fmt.Errorf("tool has no function definition")
}
// Check if tool has parameters
if toolFunc.Parameters == nil {
// No parameters needed
return &ToolChoice{
Name: toolFunc.Name,
Arguments: make(map[string]any),
}, nil
}
conv := conversation
if o.forceReasoning && reasoning != "" {
// Step 1: Get parameter-specific reasoning from LLM using the reasoning tool
// This forces the LLM to output structured JSON instead of free text
prompter := o.prompts.GetPrompt(prompt.PromptParameterReasoningType)
paramPromptData := struct {
ToolName string
Parameters string
}{
ToolName: toolFunc.Name,
Parameters: formatToolParameters(toolFunc.Parameters),
}
paramPrompt, err := prompter.Render(paramPromptData)
if err != nil {
return nil, err
}
// Use decision with reasoning tool to force structured output
paramReasoningResult, err := decisionWithStreaming(o.context, llm,
append(conversation, openai.ChatCompletionMessage{
Role: "system",
Content: paramPrompt,
}),
Tools{reasoningTool()}, "reasoning", o.maxRetries, o.streamCallback)
if err != nil {
xlog.Warn("Failed to get parameter reasoning, using original reasoning", "error", err)
// Fall back to original single-step approach
conv = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: fmt.Sprintf("The tool %s should be used with the following reasoning: %s\n\n"+
"Generate the optimal parameters for this tool. Focus on quality and completeness.",
toolFunc.Name, reasoning),
},
}, conversation...)
} else {
// Step 2: Combine original reasoning with parameter-specific reasoning
enhancedReasoning := reasoning
if len(paramReasoningResult.toolChoices) > 0 {
reasoningData, _ := json.Marshal(paramReasoningResult.toolChoices[0].Arguments)
var paramResp ReasoningResponse
if err := json.Unmarshal(reasoningData, ¶mResp); err == nil && paramResp.Reasoning != "" {
enhancedReasoning = fmt.Sprintf("%s\n\nParameter Analysis:\n%s",
reasoning, paramResp.Reasoning)
}
}
// Add enhanced reasoning to conversation
conv = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: fmt.Sprintf("The tool %s should be used with the following reasoning: %s",
toolFunc.Name, enhancedReasoning),
},
}, conversation...)
}
}
// Use decision to force parameter generation
result, err := decisionWithStreaming(o.context, llm, conv, Tools{tool}, toolFunc.Name, o.maxRetries, o.streamCallback)
if err != nil {
return nil, fmt.Errorf("failed to generate parameters for tool %s: %w", toolFunc.Name, err)
}
if len(result.toolChoices) == 0 {
return nil, fmt.Errorf("no parameters generated for tool %s", toolFunc.Name)
}
return result.toolChoices[0], nil
}
// pickTool selects tools from available tools with enhanced reasoning
func pickTool(ctx context.Context, llm LLM, fragment Fragment, tools Tools, opts ...Option) (*decisionResult, error) {
o := defaultOptions()
o.Apply(opts...)
// Set the native-parts stash fresh from this Fragment before any
// tool-decision request. pickTool issues decisionWithStreaming at multiple
// sites (direct pick, reasoning, intention); a single set here covers them
// all and — being fresh (empty for text turns) — prevents any prior turn's
// audio/video parts from leaking into a decision request.
if npa, ok := llm.(NativePartsAware); ok {
npa.SetPendingNativeParts(fragment.PendingNativeParts)
}
messages := fragment.Messages
// Step 2: Build tool names list for the intention tool
toolNames := []string{}
for _, tool := range tools {
toolNames = append(toolNames, tool.Tool().Function.Name)
}
xlog.Debug("[pickTool] Starting tool selection",
"tools", toolNames,
"forceReasoning", o.forceReasoning, "parallelToolExecution", o.parallelToolExecution)
// If not forcing reasoning, try direct tool selection
if !o.forceReasoning {
xlog.Debug("[pickTool] Using direct tool selection")
result, err := decisionWithStreaming(ctx, llm, messages, tools, "", o.maxRetries, o.streamCallback)
if err != nil {
return nil, fmt.Errorf("tool selection failed: %w", err)
}
xlog.Debug("[pickTool] Tools selected", "count", len(result.toolChoices))
return result, nil
}
// Force reasoning approach
xlog.Debug("[pickTool] Using forced reasoning approach with intention tool", "forceReasoningTool", o.forceReasoningTool)
var reasoning string
// Step 1: Get the LLM to reason about what tool to use
// Only use the reasoning tool if forceReasoningTool is enabled
// Use decision with the reasoning tool to force structured output
// This prevents the LLM from accidentally outputting tool call JSON as text
reasoningPrompt := "Analyze the current situation and available tools. " +
"Provide detailed reasoning about which tool would be most appropriate and why. " +
"Consider the task requirements and tool capabilities.\n\n" +
"Available tools:\n"
for _, tool := range tools {
toolFunc := tool.Tool().Function
if toolFunc != nil {
reasoningPrompt += fmt.Sprintf("- %s: %s\n", toolFunc.Name, toolFunc.Description)
}
}
reasoningResult, err := decisionWithStreaming(ctx, llm,
append(messages, openai.ChatCompletionMessage{
Role: "user",
Content: reasoningPrompt,
}),
Tools{reasoningTool()}, "reasoning", o.maxRetries, o.streamCallback)
if err != nil {
return nil, fmt.Errorf("failed to get reasoning: %w", err)
}
// Extract reasoning from the tool call response
if len(reasoningResult.toolChoices) > 0 {
reasoningData, _ := json.Marshal(reasoningResult.toolChoices[0].Arguments)
var reasoningResponse ReasoningResponse
if err := json.Unmarshal(reasoningData, &reasoningResponse); err != nil {
return nil, fmt.Errorf("failed to parse reasoning response: %w", err)
}
reasoning = reasoningResponse.Reasoning
}
xlog.Debug("[pickTool] Got reasoning", "reasoning", reasoning)
// Step 2: Build tool names list for the intention tool
toolNames = []string{}
for _, tool := range tools {
if tool.Tool().Function != nil {
toolNames = append(toolNames, tool.Tool().Function.Name)
}
}
// Step 3: Force the LLM to pick tools using the appropriate intention tool
xlog.Debug(
"[pickTool] Forcing tool pick via intention tool",
"available_tools", toolNames,
"parallel", o.parallelToolExecution,
)
sinkStateName := ""
if o.sinkState {
sinkStateName = o.sinkStateTool.Tool().Function.Name
}
var intentionTools Tools
intentionToolName := ""
if o.parallelToolExecution {
if o.sinkState {
intentionToolName = "pick_tools"
}
intentionTools = Tools{intentionToolMultiple(toolNames, sinkStateName)}
} else {
if o.sinkState {
intentionToolName = "pick_tool"
}
intentionTools = Tools{intentionToolSingle(toolNames, sinkStateName)}
}
intentionMessages := messages
if reasoning != "" {
intentionMessages = append(intentionMessages, openai.ChatCompletionMessage{
Role: "assistant",
Content: reasoning,
})
}
intentionResult, err := decisionWithStreaming(ctx, llm,
intentionMessages,
intentionTools, intentionToolName, o.maxRetries, o.streamCallback)
if err != nil {
return nil, fmt.Errorf("failed to pick tool via intention: %w", err)
}
if len(intentionResult.toolChoices) == 0 {
xlog.Debug("[pickTool] No tool picked from intention")
return &decisionResult{message: intentionResult.message, reasoning: reasoning}, nil
}
if reasoning == "" {
reasoning = intentionResult.reasoning
}
// Step 4: Extract the chosen tool name(s)
var toolChoices []*ToolChoice
var hasSinkState bool
if o.parallelToolExecution {
// Multiple tool selection
var intentionResponse IntentionResponseMultiple
intentionData, _ := json.Marshal(intentionResult.toolChoices[0].Arguments)
if err := json.Unmarshal(intentionData, &intentionResponse); err != nil {
return nil, fmt.Errorf("failed to unmarshal intention response: %w", err)
}
intentionReasoning := reasoning
if intentionReasoning == "" {
intentionReasoning = intentionResponse.Reasoning
}
for _, toolName := range intentionResponse.Tools {
if o.sinkState && toolName == o.sinkStateTool.Tool().Function.Name {
hasSinkState = true
xlog.Debug("[pickTool] Sink state detected in multiple selection", "hasSinkState", hasSinkState)
continue
}
chosenTool := tools.Find(toolName)
if chosenTool == nil {
xlog.Debug("[pickTool] Chosen tool not found", "tool", toolName)
continue
}
toolChoices = append(toolChoices, &ToolChoice{
Name: toolName,
Arguments: make(map[string]any),
Reasoning: intentionReasoning,
})
}
} else {
// Single tool selection - wrap in array
var intentionResponse IntentionResponseSingle
intentionData, _ := json.Marshal(intentionResult.toolChoices[0].Arguments)
if err := json.Unmarshal(intentionData, &intentionResponse); err != nil {
return nil, fmt.Errorf("failed to unmarshal intention response: %w", err)
}
intentionReasoning := reasoning
if intentionReasoning == "" {
intentionReasoning = intentionResponse.Reasoning
}
if intentionResponse.Tool == "" {
xlog.Debug("[pickTool] No tool selected")
return nil, fmt.Errorf("no tool selected")
}
chosenTool := tools.Find(intentionResponse.Tool)
if chosenTool == nil {
xlog.Debug("[pickTool] Chosen tool not found", "tool", intentionResponse.Tool)
return nil, fmt.Errorf("chosen tool not found")
}
toolChoices = append(toolChoices, &ToolChoice{
Name: intentionResponse.Tool,
Arguments: make(map[string]any),
Reasoning: intentionReasoning,
})
}
xlog.Debug("[pickTool] Tools selected via intention", "count", len(toolChoices), "hasSinkState", hasSinkState)
if hasSinkState {
xlog.Debug("[pickTool] Sink state found, returning tools to execute first", "tool_count", len(toolChoices))
}
// Return the tool choices without parameters - they'll be generated separately
return &decisionResult{toolChoices: toolChoices, reasoning: reasoning, usage: intentionResult.usage}, nil
}
func decideToPlan(llm LLM, f Fragment, tools Tools, opts ...Option) (bool, error) {
o := defaultOptions()
o.Apply(opts...)
prompter := o.prompts.GetPrompt(prompt.PromptPlanDecisionType)
additionalContext := ""
if f.ParentFragment != nil {
if o.deepContext {
additionalContext = f.ParentFragment.AllFragmentsStrings()
} else {
additionalContext = f.ParentFragment.String()
}
}
xlog.Debug("definitions", "tools", tools.Definitions())
prompt, err := prompter.Render(
struct {
Context string
Tools []*openai.FunctionDefinition
AdditionalContext string
}{
Context: f.String(),
Tools: tools.Definitions(),
AdditionalContext: additionalContext,
},
)
if err != nil {
return false, fmt.Errorf("failed to render content improver prompt: %w", err)
}
planDecision, err := llm.Ask(o.context, NewEmptyFragment().AddMessage("user", prompt))
if err != nil {
return false, fmt.Errorf("failed to ask LLM for plan decision: %w", err)
}
boolean, err := ExtractBoolean(llm, planDecision, opts...)
if err != nil {
return false, fmt.Errorf("failed extracting boolean: %w", err)
}
return boolean.Boolean, nil
}
func doPlan(llm LLM, f Fragment, tools Tools, opts ...Option) (Fragment, bool, error) {
planDecision, err := decideToPlan(llm, f, tools, opts...)
if err != nil {
return f, false, fmt.Errorf("failed to decide if planning is needed: %w", err)
}
if planDecision {
xlog.Debug("Planning is needed")
goal, err := ExtractGoal(llm, f, opts...)
if err != nil {
return f, false, fmt.Errorf("failed to extract goal: %w", err)
}
xlog.Debug("Extracted goal from Plan", "goal", goal.Goal)
plan, err := ExtractPlan(llm, f, goal, opts...)
if err != nil {
return f, false, fmt.Errorf("failed to extract plan: %w", err)
}
xlog.Debug("Extracted plan subtasks", "goal", goal.Goal, "subtasks", plan.Subtasks)
xlog.Debug("Plan description", "description", plan.Description)
// opts without autoplan disabled
f, err = ExecutePlan(llm, f, plan, goal, append(opts, func(o *Options) { o.autoPlan = false })...)
if err != nil {
return f, false, fmt.Errorf("failed to execute plan: %w", err)
}
return f, true, nil
}
return f, false, nil
}
func toolSelection(llm LLM, f Fragment, tools Tools, guidelines Guidelines, toolPrompts []openai.ChatCompletionMessage, opts ...Option) (Fragment, []*ToolChoice, bool, string, error) {
o := defaultOptions()
o.Apply(opts...)
xlog.Debug("[toolSelection] Starting tool selection", "tools_count", len(tools), "forceReasoning", o.forceReasoning)
// Build the conversation for tool selection
messages := slices.Clone(f.Messages)
// Add guidelines to the conversation if available
if len(guidelines) > 0 {
guidelinesPrompt := "Guidelines to consider when selecting tools:\n"
for i, guideline := range guidelines {
guidelinesPrompt += fmt.Sprintf("%d. If %s then %s", i+1, guideline.Condition, guideline.Action)
if len(guideline.Tools) > 0 {
toolsJSON, _ := json.Marshal(guideline.Tools)
guidelinesPrompt += fmt.Sprintf(" (Suggested Tools: %s)", string(toolsJSON))
}
guidelinesPrompt += "\n"
}
// Prepend guidelines as a system message
messages = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: guidelinesPrompt,
},
}, messages...)
}
// Add additional prompts if provided
if len(toolPrompts) > 0 {
// Prepend additional prompts to conversation
messages = append(toolPrompts, messages...)
}
if o.messagesManipulator != nil {
messages = o.messagesManipulator(messages)
}
if o.sinkState {
xlog.Debug("[toolSelection] Sink state enabled, adding to the available tools", "sink", o.sinkStateTool.Tool().Function.Name)
tools = append(tools, o.sinkStateTool)
for _, t := range tools {
xlog.Debug("[toolSelection] tool=", "tool", t.Tool().Function.Name)
}
}
// Use the enhanced pickTool function
results, err := pickTool(o.context, llm, Fragment{Messages: messages}, tools, opts...)
if err != nil {
return f, nil, false, "", fmt.Errorf("failed to pick tool: %w", err)
}
selectedTools, reasoning := results.toolChoices, results.reasoning
if len(selectedTools) == 0 {
f.Status.LastUsage = results.usage
if o.sinkState && results.message != "" {
// When sink state is enabled and the LLM replied with text instead of
// calling a tool, treat it as equivalent to calling the sink state
// (the LLM chose to reply rather than use a tool).
xlog.Debug("[toolSelection] No tool selected but LLM replied (sink state equivalent)", "message", results.message)
o.reasoningCallback(reasoning)
return f, nil, true, results.message, nil
}
// No tool was selected, reasoning contains the response
xlog.Debug("[toolSelection] No tool selected", "reasoning", reasoning)
o.statusCallback(reasoning)
o.reasoningCallback(reasoning)
return f, nil, true, results.message, nil
}
if reasoning != "" {
o.reasoningCallback(reasoning)
}
for _, t := range selectedTools {
xlog.Debug("[toolSelection] Tool selected", "name", t.Name)
}
xlog.Debug("[toolSelection] Tools selected", "count", len(selectedTools), "reasoning", reasoning)