-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsyndicate.go
More file actions
350 lines (299 loc) · 9.38 KB
/
syndicate.go
File metadata and controls
350 lines (299 loc) · 9.38 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
package syndicate
import (
"context"
"fmt"
"sync"
)
// Syndicate defines the interface for managing multiple agents and pipelines.
type Syndicate interface {
ExecuteAgent(ctx context.Context, agentName string, options ...ExecuteAgentOption) (string, error)
ExecutePipeline(ctx context.Context, options ...PipelineOption) (string, error)
FindAgent(name string) (Agent, bool)
GetGlobalHistory() []Message
GetAgentNames() []string
GetPipeline() []string
}
// syndicate is the private implementation of the Syndicate interface.
type syndicate struct {
agents map[string]Agent // Registered agents identified by their names.
globalHistory Memory // Global conversation history shared across agents.
pipeline []string // Ordered pipeline of agent names for sequential processing.
mutex sync.RWMutex // RWMutex to ensure thread-safe access to the syndicate.
}
// SyndicateOption defines a function that configures a syndicate.
type SyndicateOption func(*syndicate) error
// WithAgent registers an agent with the syndicate using the agent's name as the key.
func WithAgent(agent Agent) SyndicateOption {
return func(s *syndicate) error {
if agent == nil {
return fmt.Errorf("agent cannot be nil")
}
name := agent.GetName()
if name == "" {
return fmt.Errorf("agent name cannot be empty")
}
s.agents[name] = agent
return nil
}
}
// WithAgents registers multiple agents with the syndicate.
func WithAgents(agents ...Agent) SyndicateOption {
return func(s *syndicate) error {
for _, agent := range agents {
if agent == nil {
return fmt.Errorf("agent cannot be nil")
}
name := agent.GetName()
if name == "" {
return fmt.Errorf("agent name cannot be empty")
}
s.agents[name] = agent
}
return nil
}
}
// WithPipeline defines the execution order (pipeline) of agents.
// For example: []string{"agent1", "agent2", "agent3"}.
func WithPipeline(pipeline ...string) SyndicateOption {
return func(s *syndicate) error {
if len(pipeline) == 0 {
return fmt.Errorf("pipeline cannot be empty")
}
// Validate that all agents in pipeline exist
for _, agentName := range pipeline {
if _, exists := s.agents[agentName]; !exists {
return fmt.Errorf("agent %s not found in syndicate", agentName)
}
}
s.pipeline = pipeline
return nil
}
}
// WithGlobalHistory sets a custom global conversation history for the syndicate.
func WithGlobalHistory(history Memory) SyndicateOption {
return func(s *syndicate) error {
if history == nil {
return fmt.Errorf("global history cannot be nil")
}
s.globalHistory = history
return nil
}
}
// NewSyndicate creates a new Syndicate with the provided options.
func NewSyndicate(options ...SyndicateOption) (Syndicate, error) {
s := &syndicate{
agents: make(map[string]Agent),
globalHistory: NewSimpleMemory(),
pipeline: []string{},
}
// Apply all options
for _, option := range options {
if err := option(s); err != nil {
return nil, fmt.Errorf("failed to apply syndicate option: %w", err)
}
}
return s, nil
}
// ExecuteAgentOption defines options for executing a single agent.
type ExecuteAgentOption func(*executeAgentRequest)
// executeAgentRequest holds parameters for executing an agent.
type executeAgentRequest struct {
userName string
input string
imageURLs []string
additionalMessages [][]Message
useGlobalHistory bool
}
// WithExecuteUserName sets the user name for agent execution.
func WithExecuteUserName(userName string) ExecuteAgentOption {
return func(r *executeAgentRequest) {
r.userName = userName
}
}
// WithExecuteInput sets the input for agent execution.
func WithExecuteInput(input string) ExecuteAgentOption {
return func(r *executeAgentRequest) {
r.input = input
}
}
// WithExecuteImages sets image URLs for agent execution.
func WithExecuteImages(imageURLs ...string) ExecuteAgentOption {
return func(r *executeAgentRequest) {
r.imageURLs = imageURLs
}
}
// WithExecuteAdditionalMessages adds additional messages for agent execution.
func WithExecuteAdditionalMessages(messages ...[]Message) ExecuteAgentOption {
return func(r *executeAgentRequest) {
r.additionalMessages = messages
}
}
// WithGlobalHistoryContext includes global history in the agent execution.
func WithGlobalHistoryContext() ExecuteAgentOption {
return func(r *executeAgentRequest) {
r.useGlobalHistory = true
}
}
// ExecuteAgent runs a specific agent with the provided options.
func (s *syndicate) ExecuteAgent(ctx context.Context, agentName string, options ...ExecuteAgentOption) (string, error) {
// Apply default values
req := &executeAgentRequest{
useGlobalHistory: true, // Default to using global history
}
// Apply all options
for _, opt := range options {
opt(req)
}
// Validate required fields
if req.userName == "" {
return "", fmt.Errorf("user name is required")
}
if req.input == "" {
return "", fmt.Errorf("input is required")
}
// Retrieve the agent by its name
agent, exists := s.FindAgent(agentName)
if !exists {
return "", fmt.Errorf("agent not found: %s", agentName)
}
// Prepare chat options for the agent
chatOptions := []ChatOption{
WithUserName(req.userName),
WithInput(req.input),
}
// Add images if provided
if len(req.imageURLs) > 0 {
chatOptions = append(chatOptions, WithImages(req.imageURLs...))
}
// Add global history as additional messages if requested
if req.useGlobalHistory {
s.mutex.RLock()
globalMessages := s.globalHistory.Get()
s.mutex.RUnlock()
if len(globalMessages) > 0 {
chatOptions = append(chatOptions, WithAdditionalMessages(globalMessages))
}
}
// Add any additional messages
for _, msgs := range req.additionalMessages {
chatOptions = append(chatOptions, WithAdditionalMessages(msgs))
}
// Execute the agent
response, err := agent.Chat(ctx, chatOptions...)
if err != nil {
return "", fmt.Errorf("error executing agent %s: %w", agentName, err)
}
// Update global history
s.mutex.Lock()
s.globalHistory.Add(Message{
Role: RoleUser,
Content: req.input,
Name: req.userName,
})
// Prefix the agent's response with its name for clarity in global history
prefixedResponse := fmt.Sprintf("[%s]: %s", agentName, response)
s.globalHistory.Add(Message{
Role: RoleAssistant,
Content: prefixedResponse,
Name: agentName,
})
s.mutex.Unlock()
return response, nil
}
// PipelineOption defines options for pipeline execution.
type PipelineOption func(*pipelineRequest)
// pipelineRequest holds parameters for pipeline execution.
type pipelineRequest struct {
userName string
input string
imageURLs []string
}
// WithPipelineUserName sets the user name for pipeline execution.
func WithPipelineUserName(userName string) PipelineOption {
return func(r *pipelineRequest) {
r.userName = userName
}
}
// WithPipelineInput sets the input for pipeline execution.
func WithPipelineInput(input string) PipelineOption {
return func(r *pipelineRequest) {
r.input = input
}
}
// WithPipelineImages sets image URLs for pipeline execution (only for first agent).
func WithPipelineImages(imageURLs ...string) PipelineOption {
return func(r *pipelineRequest) {
r.imageURLs = imageURLs
}
}
// ExecutePipeline runs a sequence of agents as defined in the syndicate's pipeline.
func (s *syndicate) ExecutePipeline(ctx context.Context, options ...PipelineOption) (string, error) {
if len(s.pipeline) == 0 {
return "", fmt.Errorf("no pipeline defined in syndicate")
}
// Apply default values
req := &pipelineRequest{}
// Apply all options
for _, opt := range options {
opt(req)
}
// Validate required fields
if req.userName == "" {
return "", fmt.Errorf("user name is required")
}
if req.input == "" {
return "", fmt.Errorf("input is required")
}
currentInput := req.input
var currentImages []string = req.imageURLs // Images only for first agent
// Iterate over each agent in the defined pipeline
for i, agentName := range s.pipeline {
executeOptions := []ExecuteAgentOption{
WithExecuteUserName(req.userName),
WithExecuteInput(currentInput),
WithGlobalHistoryContext(),
}
// Only add images to the first agent in the pipeline
if i == 0 && len(currentImages) > 0 {
executeOptions = append(executeOptions, WithExecuteImages(currentImages...))
}
resp, err := s.ExecuteAgent(ctx, agentName, executeOptions...)
if err != nil {
return "", fmt.Errorf("error in agent %s: %w", agentName, err)
}
currentInput = resp
currentImages = nil // Clear images after first agent
}
return currentInput, nil
}
// FindAgent retrieves a registered agent by its name in a thread-safe manner.
func (s *syndicate) FindAgent(name string) (Agent, bool) {
s.mutex.RLock()
defer s.mutex.RUnlock()
agent, exists := s.agents[name]
return agent, exists
}
// GetGlobalHistory returns a copy of the global conversation history.
func (s *syndicate) GetGlobalHistory() []Message {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.globalHistory.Get()
}
// GetAgentNames returns a list of all registered agent names.
func (s *syndicate) GetAgentNames() []string {
s.mutex.RLock()
defer s.mutex.RUnlock()
names := make([]string, 0, len(s.agents))
for name := range s.agents {
names = append(names, name)
}
return names
}
// GetPipeline returns a copy of the current pipeline.
func (s *syndicate) GetPipeline() []string {
s.mutex.RLock()
defer s.mutex.RUnlock()
pipeline := make([]string, len(s.pipeline))
copy(pipeline, s.pipeline)
return pipeline
}