-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathagent.go
More file actions
1464 lines (1270 loc) · 41.5 KB
/
agent.go
File metadata and controls
1464 lines (1270 loc) · 41.5 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 agent
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/mudler/cogito"
"github.com/mudler/cogito/clients"
"github.com/mudler/xlog"
"github.com/mudler/LocalAGI/core/action"
"github.com/mudler/LocalAGI/core/scheduler"
"github.com/mudler/LocalAGI/core/types"
"github.com/mudler/LocalAGI/pkg/llm"
"github.com/sashabaranov/go-openai"
)
const (
UserRole = "user"
AssistantRole = "assistant"
SystemRole = "system"
)
// NoToolToCallArgs defines the arguments for the no_tool_to_call sink state tool
type NoToolToCallArgs struct {
Reasoning string `json:"reasoning" description:"The reasoning for why no tool is being called"`
}
// NoToolToCallTool is a custom sink state tool that logs when no other tool is needed
type NoToolToCallTool struct{}
// Run executes the no_tool_to_call tool and logs a message
func (t NoToolToCallTool) Run(args NoToolToCallArgs) (string, any, error) {
xlog.Info("No tool to call - agent decided no action was needed", "reasoning", args.Reasoning)
return fmt.Sprintf("No action needed: %s", args.Reasoning), nil, nil
}
type Agent struct {
sync.Mutex
options *options
Character Character
client *openai.Client
jobQueue chan *types.Job
context *types.ActionContext
currentState *types.AgentInternalState
selfEvaluationInProgress bool
pause bool
newConversations chan *types.ConversationMessage
mcpClient *mcp.Client
mcpSessions []*mcp.ClientSession
mcpServerSessions map[*MCPServer]*mcp.ClientSession
mcpSessionActions map[*mcp.ClientSession]types.Actions
subscriberMutex sync.Mutex
newMessagesSubscribers []func(*types.ConversationMessage)
observer Observer
llm cogito.LLM
sharedState *types.AgentSharedState
// Task scheduler for managing reminders
taskScheduler *scheduler.Scheduler
// currentJobByConversation tracks the running job per conversation_id for cancel-previous-on-new-message
currentJobByConversation map[string]*types.Job
currentJobMu sync.Mutex
}
type RAGDB interface {
Store(s string) error
Reset() error
Search(s string, similarEntries int) ([]string, error)
Count() int
}
func New(opts ...Option) (*Agent, error) {
options, err := newOptions(opts...)
if err != nil {
return nil, fmt.Errorf("failed to set options: %v", err)
}
client := llm.NewClient(options.LLMAPI.APIKey, options.LLMAPI.APIURL, options.timeout)
llmClient := clients.NewLocalAILLM(options.LLMAPI.Model, options.LLMAPI.APIKey, options.LLMAPI.APIURL)
c := context.Background()
if options.context != nil {
c = options.context
}
ctx, cancel := context.WithCancel(c)
a := &Agent{
jobQueue: make(chan *types.Job),
options: options,
client: client,
Character: options.character,
currentState: &types.AgentInternalState{},
llm: llmClient,
context: types.NewActionContext(ctx, cancel),
newConversations: make(chan *types.ConversationMessage),
newMessagesSubscribers: options.newConversationsSubscribers,
sharedState: types.NewAgentSharedState(options.lastMessageDuration),
currentJobByConversation: make(map[string]*types.Job),
mcpClient: mcp.NewClient(&mcp.Implementation{Name: "LocalAI", Version: "v1.0.0"}, nil),
mcpServerSessions: make(map[*MCPServer]*mcp.ClientSession),
mcpSessionActions: make(map[*mcp.ClientSession]types.Actions),
}
// Initialize observer if provided
if options.observer != nil {
a.observer = options.observer
}
if a.options.statefile != "" {
if _, err := os.Stat(a.options.statefile); err == nil {
if err = a.LoadState(a.options.statefile); err != nil {
return a, fmt.Errorf("failed to load state: %v", err)
}
}
}
// var programLevel = new(xlog.LevelVar) // Info by default
// h := xlog.NewTextHandler(os.Stdout, &xlog.HandlerOptions{Level: programLevel})
// xlog = xlog.New(h)
//programLevel.Set(a.options.logLevel)
if err := a.prepareIdentity(); err != nil {
return nil, fmt.Errorf("failed to prepare identity: %v", err)
}
xlog.Info("Populating actions from MCP Servers (if any)")
a.initMCPActions()
xlog.Info("Done populating actions from MCP Servers")
// Initialize task scheduler for reminders
schedulerPath := options.schedulerStorePath
if schedulerPath == "" {
schedulerPath = "scheduled_tasks.json"
}
store, err := scheduler.NewJSONStore(schedulerPath)
if err != nil {
return nil, fmt.Errorf("failed to create scheduler store: %v", err)
}
executor := &agentSchedulerExecutor{agent: a}
pollInterval := options.schedulerPollInterval
if pollInterval == 0 {
pollInterval = 30 * time.Second
}
a.taskScheduler = scheduler.NewScheduler(store, executor, pollInterval)
a.sharedState.Scheduler = a.taskScheduler
a.sharedState.AgentName = a.Character.Name
xlog.Info("Task scheduler initialized", "store_path", schedulerPath, "poll_interval", pollInterval)
xlog.Info(
"Agent created",
"agent", a.Character.Name,
"character", a.Character.String(),
"state", a.State().String(),
"goal", a.options.permanentGoal,
"model", a.options.LLMAPI.Model,
)
return a, nil
}
func (a *Agent) SharedState() *types.AgentSharedState {
return a.sharedState
}
func (a *Agent) startNewConversationsConsumer() {
go func() {
for {
select {
case <-a.context.Done():
return
case msg := <-a.newConversations:
xlog.Debug("New conversation", "agent", a.Character.Name, "message", msg.Message.Content)
a.subscriberMutex.Lock()
subs := a.newMessagesSubscribers
a.subscriberMutex.Unlock()
for _, s := range subs {
if s != nil && msg != nil {
s(msg)
}
}
}
}
}()
}
func (a *Agent) AddSubscriber(f func(*types.ConversationMessage)) {
a.subscriberMutex.Lock()
defer a.subscriberMutex.Unlock()
a.newMessagesSubscribers = append(a.newMessagesSubscribers, f)
}
func (a *Agent) Context() context.Context {
return a.context.Context
}
// Ask is a blocking call that returns the response as soon as it's ready.
// It discards any other computation.
func (a *Agent) Ask(opts ...types.JobOption) *types.JobResult {
xlog.Debug("Agent Ask()", "agent", a.Character.Name, "model", a.options.LLMAPI.Model)
defer func() {
xlog.Debug("Agent has finished being asked", "agent", a.Character.Name)
}()
if a.observer != nil {
obs := a.observer.NewObservable()
obs.Name = "job"
obs.Icon = "plug"
a.observer.Update(*obs)
opts = append(opts, types.WithObservable(obs))
}
return a.Execute(types.NewJob(
append(
opts,
types.WithReasoningCallback(a.options.reasoningCallback),
types.WithResultCallback(a.options.resultCallback),
)...,
))
}
// Ask is a pre-emptive, blocking call that returns the response as soon as it's ready.
// It discards any other computation.
func (a *Agent) Execute(j *types.Job) *types.JobResult {
xlog.Debug("Agent Execute()", "agent", a.Character.Name, "model", a.options.LLMAPI.Model)
defer func() {
xlog.Debug("Agent has finished", "agent", a.Character.Name)
}()
if j.Obs != nil && a.observer != nil {
if len(j.ConversationHistory) > 0 {
m := j.ConversationHistory[len(j.ConversationHistory)-1]
j.Obs.Creation = &types.Creation{ChatCompletionMessage: &m}
a.observer.Update(*j.Obs)
}
j.Result.AddFinalizer(func(ccm []openai.ChatCompletionMessage) {
if a.observer == nil {
return
}
// Merge into existing Completion so last-progress completion data is preserved
if j.Obs.Completion == nil {
j.Obs.Completion = &types.Completion{}
}
j.Obs.Completion.Conversation = ccm
if j.Result.Error != nil {
j.Obs.Completion.Error = j.Result.Error.Error()
}
a.observer.Update(*j.Obs)
})
}
a.Enqueue(j)
result, err := j.Result.WaitResult(a.context.Context)
if err != nil {
return nil
}
return result
}
func (a *Agent) Enqueue(j *types.Job) {
j.ReasoningCallback = a.options.reasoningCallback
j.ResultCallback = a.options.resultCallback
// Cancel previous running job for this conversation if option is enabled
cancelPrevious := a.options.cancelPreviousOnNewMessage == nil || *a.options.cancelPreviousOnNewMessage
if cancelPrevious && j.Metadata != nil {
if convID, ok := j.Metadata[types.MetadataKeyConversationID].(string); ok && convID != "" {
a.currentJobMu.Lock()
existing := a.currentJobByConversation[convID]
a.currentJobMu.Unlock()
if existing != nil {
existing.Cancel()
}
}
}
a.jobQueue <- j
}
func (a *Agent) Transcribe(ctx context.Context, file string) (string, error) {
resp, err := a.client.CreateTranscription(ctx,
openai.AudioRequest{
Model: a.options.LLMAPI.TranscriptionModel,
Language: a.options.LLMAPI.TranscriptionLanguage,
FilePath: file,
},
)
if err != nil {
return "", err
}
return resp.Text, nil
}
func (a *Agent) TTS(ctx context.Context, text string) ([]byte, error) {
if a.options.LLMAPI.TTSModel == "" {
return nil, fmt.Errorf("TTS model is not set")
}
resp, err := a.client.CreateSpeech(ctx,
openai.CreateSpeechRequest{
Model: openai.SpeechModel(a.options.LLMAPI.TTSModel),
Input: text,
ResponseFormat: openai.SpeechResponseFormatMp3,
},
)
if err != nil {
return nil, err
}
defer resp.Close()
buf := bytes.NewBuffer(nil)
io.Copy(buf, resp)
return buf.Bytes(), nil
}
var ErrContextCanceled = fmt.Errorf("context canceled")
func (a *Agent) Stop() {
xlog.Debug("Stopping agent", "agent", a.Character.Name)
// Stop the scheduler
a.taskScheduler.Stop()
xlog.Info("Task scheduler stopped")
a.Lock()
defer a.Unlock()
a.closeMCPServers()
a.context.Cancel()
}
func (a *Agent) Pause() {
a.Lock()
defer a.Unlock()
a.pause = true
}
func (a *Agent) Resume() {
a.Lock()
defer a.Unlock()
a.pause = false
}
func (a *Agent) Paused() bool {
a.Lock()
defer a.Unlock()
return a.pause
}
func (a *Agent) Memory() RAGDB {
return a.options.ragdb
}
func (a *Agent) processPrompts(ctx context.Context, conversation Messages) Messages {
// Add custom prompts
for _, prompt := range a.options.prompts {
message, err := prompt.Render(a)
if err != nil {
xlog.Error("Error rendering prompt", "error", err)
continue
}
if message.Content == "" && message.ImageBase64 == "" {
xlog.Debug("Prompt is empty, skipping", "agent", a.Character.Name)
continue
}
content := message.Content
if strings.Contains(content, "{{") {
promptTemplate, err := templateBase("template", content)
if err != nil {
xlog.Error("Error rendering template", "error", err)
}
content, err = templateExecute(promptTemplate, CommonTemplateData{AgentName: a.Character.Name})
if err != nil {
xlog.Error("Error executing template", "error", err)
content = message.Content
}
}
if message.ImageBase64 != "" {
// iF model support both images and text, process it as a single multicontent message and return
if !a.options.SeparatedMultimodalModel() {
conversation = append([]openai.ChatCompletionMessage{
{
Role: prompt.Role(),
MultiContent: []openai.ChatMessagePart{
{
Type: openai.ChatMessagePartTypeText,
Text: content,
},
{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: message.ImageBase64,
},
},
},
}}, conversation...)
} else {
// We need to describe the image first, and we will process the text separately (we do not return here)
imageDescription, err := a.describeImage(ctx, a.options.LLMAPI.MultimodalModel, message.ImageBase64)
if err != nil {
xlog.Error("Error describing image", "error", err)
} else {
conversation = append([]openai.ChatCompletionMessage{
{
Role: prompt.Role(),
Content: fmt.Sprintf("%s\n\nImage description: %s", content, imageDescription),
}}, conversation...)
}
}
} else {
conversation = append([]openai.ChatCompletionMessage{
{
Role: prompt.Role(),
Content: content,
}}, conversation...)
}
}
// TODO: move to a Promptblock?
if a.options.systemPrompt != "" {
content := a.options.systemPrompt
if strings.Contains(content, "{{") {
promptTemplate, err := templateBase("template", a.options.systemPrompt)
if err != nil {
xlog.Error("Error rendering template", "error", err)
}
content, err = templateExecute(promptTemplate, CommonTemplateData{AgentName: a.Character.Name})
if err != nil {
xlog.Error("Error executing template", "error", err)
content = a.options.systemPrompt
}
}
if !conversation.Exist(content) {
conversation = append([]openai.ChatCompletionMessage{
{
Role: "system",
Content: content,
}}, conversation...)
}
}
return conversation
}
func (a *Agent) describeImage(ctx context.Context, model, imageURL string) (string, error) {
xlog.Debug("Describing image", "model", model)
resp, err := a.client.CreateChatCompletion(ctx,
openai.ChatCompletionRequest{
Model: model,
Messages: []openai.ChatCompletionMessage{
{
Role: "user",
MultiContent: []openai.ChatMessagePart{
{
Type: openai.ChatMessagePartTypeText,
Text: "What is in the image?",
},
{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: imageURL,
},
},
},
},
}})
if err != nil {
return "", err
}
if len(resp.Choices) == 0 {
return "", fmt.Errorf("no choices")
}
xlog.Debug("Described image", "description", resp.Choices[0].Message.Content)
return resp.Choices[0].Message.Content, nil
}
// extractAllImageContent extracts all images from a message
func extractAllImageContent(message openai.ChatCompletionMessage) (images []string, text string, e error) {
e = fmt.Errorf("no image found")
if message.MultiContent != nil {
for _, content := range message.MultiContent {
if content.Type == openai.ChatMessagePartTypeImageURL {
images = append(images, content.ImageURL.URL)
e = nil
}
if content.Type == openai.ChatMessagePartTypeText {
text = content.Text
e = nil
}
}
}
return
}
func (a *Agent) processUserInputs(conv Messages) Messages {
// walk conversation history, and check if any message contains images.
// If they do, we need to describe the images first with a model that supports image understanding (if the current model doesn't support it)
// and add them to the conversation context
if !a.options.SeparatedMultimodalModel() {
return conv
}
xlog.Debug("Processing user inputs", "agent", a.Character.Name, "conversation", conv)
// Process all messages in the conversation to extract and describe images
var processedMessages Messages
var messagesToRemove []int
for i, message := range conv {
images, text, err := extractAllImageContent(message)
if err == nil && len(images) > 0 {
xlog.Debug("Found images in message", "messageIndex", i, "imageCount", len(images), "role", message.Role)
// Mark this message for removal
messagesToRemove = append(messagesToRemove, i)
// Process each image in the message
var imageDescriptions []string
for j, image := range images {
imageDescription, err := a.describeImage(a.context.Context, a.options.LLMAPI.MultimodalModel, image)
if err != nil {
xlog.Error("Error describing image", "error", err, "messageIndex", i, "imageIndex", j)
imageDescriptions = append(imageDescriptions, fmt.Sprintf("Image %d: [Error describing image: %v]", j+1, err))
} else {
imageDescriptions = append(imageDescriptions, fmt.Sprintf("Image %d: %s", j+1, imageDescription))
}
}
// Add the text content as a new message with the same role first
if text != "" {
imageDesc := fmt.Sprintf("\n\n[Images in this message: %s]", strings.Join(imageDescriptions, "; "))
textMessage := openai.ChatCompletionMessage{
Role: message.Role,
Content: text + imageDesc,
}
processedMessages = append(processedMessages, textMessage)
} else {
// Images only: emit a single user message with the image description
content := fmt.Sprintf("[Attached images: %s]", strings.Join(imageDescriptions, "; "))
processedMessages = append(processedMessages, openai.ChatCompletionMessage{
Role: message.Role,
Content: content,
})
}
} else {
// No image found, keep the original message
processedMessages = append(processedMessages, message)
}
}
// If we found and processed any images, replace the conversation
if len(messagesToRemove) > 0 {
xlog.Info("Processed images in conversation", "messagesWithImages", len(messagesToRemove), "agent", a.Character.Name)
return processedMessages
}
return conv
}
func (a *Agent) filterJob(job *types.Job) (ok bool, err error) {
hasTriggers := false
triggeredBy := ""
failedBy := ""
if job.DoneFilter {
return true, nil
}
job.DoneFilter = true
if len(a.options.jobFilters) < 1 {
xlog.Debug("No filters")
return true, nil
}
for _, filter := range a.options.jobFilters {
name := filter.Name()
if triggeredBy != "" && filter.IsTrigger() {
continue
}
ok, err = filter.Apply(job)
if err != nil {
xlog.Error("Error in job filter", "filter", name, "error", err)
failedBy = name
break
}
if filter.IsTrigger() {
hasTriggers = true
if ok {
triggeredBy = name
xlog.Info("Job triggered by filter", "filter", name)
}
} else if !ok {
failedBy = name
xlog.Info("Job failed filter", "filter", name)
break
} else {
xlog.Debug("Job passed filter", "filter", name)
}
}
if a.Observer() != nil && job.Obs != nil {
obs := a.Observer().NewObservable()
obs.Name = "filter"
obs.Icon = "shield"
obs.ParentID = job.Obs.ID
if err == nil {
obs.Completion = &types.Completion{
FilterResult: &types.FilterResult{
HasTriggers: hasTriggers,
TriggeredBy: triggeredBy,
FailedBy: failedBy,
},
}
} else {
obs.Completion = &types.Completion{
Error: err.Error(),
}
}
a.Observer().Update(*obs)
}
return failedBy == "" && (!hasTriggers || triggeredBy != ""), nil
}
// replyWithToolCall handles user-defined actions by recording the action state without setting Response
func (a *Agent) replyWithToolCall(job *types.Job, conv []openai.ChatCompletionMessage, params types.ActionParams, chosenAction types.Action, reasoning string) {
// Record the action state so the webui can detect this is a user-defined action
stateResult := types.ActionState{
ActionCurrentState: types.ActionCurrentState{
Job: job,
Action: chosenAction,
Params: params,
Reasoning: reasoning,
},
ActionResult: types.ActionResult{
Result: reasoning, // The reasoning/message to show to user
},
}
// Add the action state to the job result
job.Result.SetResult(stateResult)
// Used by the observer
conv = append(conv, openai.ChatCompletionMessage{
Role: "assistant",
ToolCalls: []openai.ToolCall{
{
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: chosenAction.Definition().ToFunctionDefinition().Name,
Arguments: params.String(),
},
},
},
})
// Set conversation but leave Response empty
// The webui will detect the user-defined action and generate the proper tool call response
job.Result.Conversation = conv
// job.Result.Response remains empty - this signals to webui that it should check State
job.Result.Finish(nil)
}
// validateBuiltinTools checks that builtin tools specified by the user can be matched to available actions
func (a *Agent) validateBuiltinTools(job *types.Job) {
builtinTools := job.GetBuiltinTools()
if len(builtinTools) == 0 {
return
}
// Get available actions
availableActions := a.availableActions(job)
for _, tool := range builtinTools {
functionName := tool.Name
// Check if this is a web search builtin tool
if strings.HasPrefix(string(functionName), "web_search_") {
// Look for a search action
searchAction := availableActions.Find("search")
if searchAction == nil {
xlog.Warn("Web search builtin tool specified but no 'search' action available",
"function_name", functionName,
"agent", a.Character.Name)
} else {
xlog.Debug("Web search builtin tool matched to search action",
"function_name", functionName,
"agent", a.Character.Name)
}
} else {
// For future builtin tools, add more matching logic here
xlog.Warn("Unknown builtin tool specified",
"function_name", functionName,
"agent", a.Character.Name)
}
}
}
func (a *Agent) addFunctionResultToConversation(ctx context.Context, chosenAction types.Action, actionParams types.ActionParams, result types.ActionResult, conv Messages) Messages {
// calling the function
conv = append(conv, openai.ChatCompletionMessage{
Role: "assistant",
ToolCalls: []openai.ToolCall{
{
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: chosenAction.Definition().Name.String(),
Arguments: actionParams.String(),
},
},
},
})
// result of calling the function
// If it contains an image, we need to put it in the conversation (if supported by the model)
if result.ImageBase64Result != "" {
// iF model support both images and text, process it as a single multicontent message and return
if !a.options.SeparatedMultimodalModel() {
conv = append(conv, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
MultiContent: []openai.ChatMessagePart{
{
Type: openai.ChatMessagePartTypeText,
Text: result.Result,
},
{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: result.ImageBase64Result,
},
},
},
Name: chosenAction.Definition().Name.String(),
ToolCallID: chosenAction.Definition().Name.String(),
})
return conv
} else {
// We need to describe the image first, and we will process the text separately (we do not return here)
imageDescription, err := a.describeImage(ctx, a.options.LLMAPI.MultimodalModel, result.ImageBase64Result)
if err != nil {
xlog.Error("Error describing image", "error", err)
} else {
conv = append(conv, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: fmt.Sprintf("Tool generated an image, the description of the image is: %s", imageDescription),
Name: chosenAction.Definition().Name.String(),
ToolCallID: chosenAction.Definition().Name.String(),
})
if result.Result != "" {
conv = append(conv, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: result.Result,
Name: chosenAction.Definition().Name.String(),
ToolCallID: chosenAction.Definition().Name.String(),
})
}
}
}
} else {
conv = append(conv, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: result.Result,
Name: chosenAction.Definition().Name.String(),
ToolCallID: chosenAction.Definition().Name.String(),
})
}
return conv
}
func (a *Agent) consumeJob(job *types.Job, role string) {
if err := job.GetContext().Err(); err != nil {
job.Result.Finish(fmt.Errorf("expired"))
return
}
a.Lock()
paused := a.pause
a.Unlock()
if paused {
xlog.Info("Agent is paused, skipping job", "agent", a.Character.Name)
job.Result.Finish(fmt.Errorf("agent is paused"))
return
}
// Register this job as the current one for its conversation (for cancel-previous-on-new-message)
var conversationID string
if job.Metadata != nil {
if cid, ok := job.Metadata[types.MetadataKeyConversationID].(string); ok && cid != "" {
conversationID = cid
a.currentJobMu.Lock()
a.currentJobByConversation[conversationID] = job
a.currentJobMu.Unlock()
}
}
if conversationID != "" {
defer func() {
a.currentJobMu.Lock()
if a.currentJobByConversation[conversationID] == job {
delete(a.currentJobByConversation, conversationID)
}
a.currentJobMu.Unlock()
}()
}
// We are self evaluating if we consume the job as a system role
selfEvaluation := role == SystemRole
conv := job.ConversationHistory
a.Lock()
a.selfEvaluationInProgress = selfEvaluation
a.Unlock()
defer job.Cancel()
if selfEvaluation {
defer func() {
a.Lock()
a.selfEvaluationInProgress = false
a.Unlock()
}()
}
// Ensure job observable has Creation and Completion for jobs that bypass Execute() (e.g. periodic, scheduler)
if job.Obs != nil && a.observer != nil {
if job.Obs.Creation == nil && len(job.ConversationHistory) > 0 {
m := job.ConversationHistory[len(job.ConversationHistory)-1]
job.Obs.Creation = &types.Creation{ChatCompletionMessage: &m}
a.observer.Update(*job.Obs)
}
job.Result.AddFinalizer(func(ccm []openai.ChatCompletionMessage) {
if a.observer == nil {
return
}
if job.Obs.Completion == nil {
job.Obs.Completion = &types.Completion{}
}
job.Obs.Completion.Conversation = ccm
if job.Result.Error != nil {
job.Obs.Completion.Error = job.Result.Error.Error()
}
a.observer.Update(*job.Obs)
})
}
conv = a.processPrompts(job.GetContext(), conv)
if ok, err := a.filterJob(job); !ok || err != nil {
if err != nil {
job.Result.Finish(fmt.Errorf("Error in job filter: %w", err))
} else {
job.Result.Finish(nil)
}
return
}
conv = a.processUserInputs(conv)
// RAG
conv = a.knowledgeBaseLookup(job, conv)
// Validate builtin tools against available actions
a.validateBuiltinTools(job)
// Merge all leading system messages into one (self-eval, HUD, RAG, system prompt, custom prompts)
var selfEvalContent, hudContent string
if selfEvaluation {
selfEvalContent = pickSelfTemplate
}
if a.options.enableHUD {
prompt, err := renderTemplate(hudTemplate, a.prepareHUD(), a.availableActions(job), "")
if err != nil {
job.Result.Finish(fmt.Errorf("error renderTemplate: %w", err))
return
}
hudContent = prompt
}
conv = Messages(conv).mergeLeadingSystemMessages(selfEvalContent, hudContent)
// Backends with enable_thinking (e.g. vLLM) reject requests where the last message is
// assistant (treated as "assistant response prefill"). We can end with assistant when:
// - Web/API: client sends previous_response_id but no new input (ToChatCompletionMessages()
// is empty), so messages = GetConversation(id) which was saved after the last reply and
// ends with assistant.
// - Connectors: if they pass a thread that was stored ending with assistant and no new
// user message is appended in that code path.
// - Periodic/scheduler jobs always use WithText(...) so they append a user message; they
// do not end with assistant.
// Normalize so we never send a request that ends with assistant (avoids enable_thinking
// error); callers should ideally always append a new user message when continuing a thread.
if len(conv) > 0 && conv[len(conv)-1].Role == AssistantRole {
conv = append(conv, openai.ChatCompletionMessage{
Role: UserRole,
Content: " ",
})
}
fragment := cogito.NewFragment(conv...)
availableActions := a.getAvailableActionsForJob(job)
cogitoTools := availableActions.ToCogitoTools(job.GetContext(), a.sharedState)
a.mcpStreamableClientHealthCheck()
allActions := availableActions
for _, session := range a.mcpSessions {
allActions = append(allActions, a.mcpSessionActions[session]...)
}
obs := job.Obs
defer func() {
if obs != nil && a.observer != nil {
obs.MakeLastProgressCompletion()
a.observer.Update(*obs)
}
}()
var err error
var userTool bool
// Set by tool callback when it decides the job outcome; Finish is then called once after ExecuteTools.
var finishedByCallback bool
var finishErr error
var observables = make(map[string]*types.Observable)
var mcpSessions = append(a.mcpSessions, a.options.extraMCPSessions...)
cogitoOpts := []cogito.Option{
cogito.WithMCPs(mcpSessions...),
cogito.WithTools(
cogitoTools...,
),
cogito.WithSinkState(
cogito.NewToolDefinition(
NoToolToCallTool{},
NoToolToCallArgs{},
"no_tool_to_call",
"Called when no other tool is needed to respond to the user",
),
),
cogito.WithReasoningCallback(func(s string) {
xlog.Debug("Cogito reasoning callback", "status", s)
if s == "" {
return
}
if a.observer != nil && job.Obs != nil {
job.Obs.AddProgress(
types.Progress{
ChatCompletionResponse: &openai.ChatCompletionResponse{
Choices: []openai.ChatCompletionChoice{
{
Message: openai.ChatCompletionMessage{
Role: "assistant",
Content: s,
},
},
},
},
})
a.observer.Update(*job.Obs)
}