-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsyndicate_test.go
More file actions
451 lines (388 loc) · 13 KB
/
syndicate_test.go
File metadata and controls
451 lines (388 loc) · 13 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
package syndicate
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
)
// syndicateTestMemory implementa la interfaz Memory para pruebas.
type syndicateTestMemory struct {
messages []Message
mu sync.Mutex
}
func (m *syndicateTestMemory) Add(msg Message) {
m.mu.Lock()
defer m.mu.Unlock()
m.messages = append(m.messages, msg)
}
func (m *syndicateTestMemory) Get() []Message {
m.mu.Lock()
defer m.mu.Unlock()
copyMessages := make([]Message, len(m.messages))
copy(copyMessages, m.messages)
return copyMessages
}
// syndicateTestAgent es una implementación simple del interface Agent para pruebas.
type syndicateTestAgent struct {
name string
memory Memory
// chatFunc simula el procesamiento del agente usando Chat.
chatFunc func(ctx context.Context, options ...ChatOption) (string, error)
}
func (f *syndicateTestAgent) Chat(ctx context.Context, options ...ChatOption) (string, error) {
if f.chatFunc != nil {
return f.chatFunc(ctx, options...)
}
// Por defecto retorna una respuesta simple
return fmt.Sprintf("response from %s", f.name), nil
}
func (f *syndicateTestAgent) GetName() string {
return f.name
}
// newSyndicateTestAgent crea un syndicateTestAgent con comportamiento personalizable.
func newSyndicateTestAgent(name string, suffix string) *syndicateTestAgent {
return &syndicateTestAgent{
name: name,
memory: &syndicateTestMemory{},
chatFunc: func(ctx context.Context, options ...ChatOption) (string, error) {
// Parsear las opciones para obtener el input - USAR EL TIPO CORRECTO
req := &chatRequest{} // Cambié testChatRequest por chatRequest
for _, opt := range options {
opt(req)
}
// Simular procesamiento del input
if req.input == "" {
return "", fmt.Errorf("input is required")
}
// Retorna el input junto con un sufijo para identificar al agente
return fmt.Sprintf("%s %s", req.input, suffix), nil
},
}
}
// TestNewSyndicate verifica la creación de syndicate con functional options.
func TestNewSyndicate(t *testing.T) {
agent1 := newSyndicateTestAgent("agent1", "->A")
agent2 := newSyndicateTestAgent("agent2", "->B")
customHistory := &syndicateTestMemory{}
syndicate, err := NewSyndicate(
WithAgent(agent1),
WithAgent(agent2),
WithGlobalHistory(customHistory),
WithPipeline("agent1", "agent2"),
)
if err != nil {
t.Fatalf("Error creando syndicate: %v", err)
}
// Verificar que los agentes estén registrados
found1, exists1 := syndicate.FindAgent("agent1")
if !exists1 || found1.GetName() != "agent1" {
t.Error("agent1 no encontrado o nombre incorrecto")
}
found2, exists2 := syndicate.FindAgent("agent2")
if !exists2 || found2.GetName() != "agent2" {
t.Error("agent2 no encontrado o nombre incorrecto")
}
// Verificar pipeline
pipeline := syndicate.GetPipeline()
if len(pipeline) != 2 || pipeline[0] != "agent1" || pipeline[1] != "agent2" {
t.Errorf("Pipeline incorrecta: %v", pipeline)
}
// Verificar global history
history := syndicate.GetGlobalHistory()
if len(history) != 0 {
t.Errorf("Historia global debería estar vacía inicialmente")
}
}
// TestNewSyndicate_WithErrors verifica validaciones en la creación del syndicate.
func TestNewSyndicate_WithErrors(t *testing.T) {
// Test con agente nil
_, err := NewSyndicate(WithAgent(nil))
if err == nil || !strings.Contains(err.Error(), "agent cannot be nil") {
t.Errorf("Se esperaba error por agente nil: %v", err)
}
// Test con agente sin nombre
agentSinNombre := &syndicateTestAgent{name: ""}
_, err = NewSyndicate(WithAgent(agentSinNombre))
if err == nil || !strings.Contains(err.Error(), "agent name cannot be empty") {
t.Errorf("Se esperaba error por agente sin nombre: %v", err)
}
// Test con pipeline vacío
agent := newSyndicateTestAgent("test", "->test")
_, err = NewSyndicate(
WithAgent(agent),
WithPipeline(),
)
if err == nil || !strings.Contains(err.Error(), "pipeline cannot be empty") {
t.Errorf("Se esperaba error por pipeline vacío: %v", err)
}
// Test con pipeline referenciando agente inexistente
_, err = NewSyndicate(
WithAgent(agent),
WithPipeline("test", "nonexistent"),
)
if err == nil || !strings.Contains(err.Error(), "agent nonexistent not found") {
t.Errorf("Se esperaba error por agente inexistente en pipeline: %v", err)
}
// Test con global history nil
_, err = NewSyndicate(WithGlobalHistory(nil))
if err == nil || !strings.Contains(err.Error(), "global history cannot be nil") {
t.Errorf("Se esperaba error por global history nil: %v", err)
}
}
// TestExecuteAgent verifica el flujo de ExecuteAgent.
func TestExecuteAgent(t *testing.T) {
agent := newSyndicateTestAgent("agent1", "->agent1")
globalHistory := &syndicateTestMemory{}
syndicate, err := NewSyndicate(
WithAgent(agent),
WithGlobalHistory(globalHistory),
)
if err != nil {
t.Fatalf("Error creando syndicate: %v", err)
}
ctx := context.Background()
resp, err := syndicate.ExecuteAgent(ctx, "agent1",
WithExecuteUserName("usuario1"),
WithExecuteInput("hola"),
)
if err != nil {
t.Fatalf("ExecuteAgent failed: %v", err)
}
// Verificar respuesta
if !strings.Contains(resp, "hola") || !strings.Contains(resp, "->agent1") {
t.Errorf("Respuesta inesperada: %s", resp)
}
// Verificar que globalHistory tenga 2 mensajes: usuario y asistente
history := globalHistory.Get()
if len(history) != 2 {
t.Errorf("Se esperaban 2 mensajes en globalHistory, se obtuvieron: %d", len(history))
}
// Verificar que el mensaje de respuesta tenga el prefijo "[agent1]: "
if !strings.HasPrefix(history[1].Content, "[agent1]:") {
t.Errorf("El mensaje de respuesta global no tiene el prefijo correcto: %s", history[1].Content)
}
}
// TestExecuteAgent_WithValidation verifica validaciones en ExecuteAgent.
func TestExecuteAgent_WithValidation(t *testing.T) {
agent := newSyndicateTestAgent("agent1", "->agent1")
syndicate, _ := NewSyndicate(WithAgent(agent))
ctx := context.Background()
// Test sin userName
_, err := syndicate.ExecuteAgent(ctx, "agent1",
WithExecuteInput("test"),
)
if err == nil || !strings.Contains(err.Error(), "user name is required") {
t.Errorf("Se esperaba error por falta de userName: %v", err)
}
// Test sin input
_, err = syndicate.ExecuteAgent(ctx, "agent1",
WithExecuteUserName("user1"),
)
if err == nil || !strings.Contains(err.Error(), "input is required") {
t.Errorf("Se esperaba error por falta de input: %v", err)
}
// Test con agente inexistente
_, err = syndicate.ExecuteAgent(ctx, "nonexistent",
WithExecuteUserName("user1"),
WithExecuteInput("test"),
)
if err == nil || !strings.Contains(err.Error(), "agent not found") {
t.Errorf("Se esperaba error por agente inexistente: %v", err)
}
}
// TestExecuteAgent_WithOptions verifica diferentes opciones de ExecuteAgent.
func TestExecuteAgent_WithOptions(t *testing.T) {
agent := newSyndicateTestAgent("agent1", "->agent1")
globalHistory := &syndicateTestMemory{}
// Agregar un mensaje previo a la historia global
globalHistory.Add(Message{Role: RoleUser, Content: "mensaje previo"})
syndicate, _ := NewSyndicate(
WithAgent(agent),
WithGlobalHistory(globalHistory),
)
ctx := context.Background()
// Test con imágenes
_, err := syndicate.ExecuteAgent(ctx, "agent1",
WithExecuteUserName("user1"),
WithExecuteInput("describe image"),
WithExecuteImages("https://example.com/image.jpg"),
)
if err != nil {
t.Errorf("Error con imágenes: %v", err)
}
// Test con mensajes adicionales
additionalMsgs := []Message{
{Role: RoleUser, Content: "contexto adicional"},
}
_, err = syndicate.ExecuteAgent(ctx, "agent1",
WithExecuteUserName("user1"),
WithExecuteInput("test with context"),
WithExecuteAdditionalMessages(additionalMsgs),
)
if err != nil {
t.Errorf("Error con mensajes adicionales: %v", err)
}
}
// TestFindAgent verifica FindAgent.
func TestFindAgent(t *testing.T) {
agent := newSyndicateTestAgent("agentX", "->X")
syndicate, _ := NewSyndicate(WithAgent(agent))
foundAgent, exists := syndicate.FindAgent("agentX")
if !exists {
t.Error("Se esperaba encontrar el agente agentX")
}
if foundAgent.GetName() != "agentX" {
t.Errorf("Nombre del agente incorrecto: se obtuvo %s", foundAgent.GetName())
}
// Verificar búsqueda de agente inexistente
_, exists = syndicate.FindAgent("no-exist")
if exists {
t.Error("No se esperaba encontrar un agente inexistente")
}
}
// TestExecutePipeline verifica la ejecución secuencial de agentes.
func TestExecutePipeline(t *testing.T) {
agent1 := newSyndicateTestAgent("agent1", "->A")
agent2 := newSyndicateTestAgent("agent2", "->B")
syndicate, err := NewSyndicate(
WithAgents(agent1, agent2),
WithPipeline("agent1", "agent2"),
)
if err != nil {
t.Fatalf("Error creando syndicate: %v", err)
}
ctx := context.Background()
finalResp, err := syndicate.ExecutePipeline(ctx,
WithPipelineUserName("usuario1"),
WithPipelineInput("inicio"),
)
if err != nil {
t.Fatalf("ExecutePipeline failed: %v", err)
}
// Se espera que cada agente agregue su sufijo al input
if !strings.Contains(finalResp, "->A") || !strings.Contains(finalResp, "->B") {
t.Errorf("Pipeline no procesada correctamente, salida: %s", finalResp)
}
}
// TestExecutePipeline_WithValidation verifica validaciones en ExecutePipeline.
func TestExecutePipeline_WithValidation(t *testing.T) {
// Syndicate sin pipeline
agent := newSyndicateTestAgent("agent1", "->A")
syndicate, _ := NewSyndicate(WithAgent(agent))
ctx := context.Background()
_, err := syndicate.ExecutePipeline(ctx,
WithPipelineUserName("usuario1"),
WithPipelineInput("inicio"),
)
if err == nil || !strings.Contains(err.Error(), "no pipeline defined") {
t.Errorf("Se esperaba error por pipeline vacío: %v", err)
}
// Syndicate con pipeline
syndicate2, _ := NewSyndicate(
WithAgent(agent),
WithPipeline("agent1"),
)
// Test sin userName
_, err = syndicate2.ExecutePipeline(ctx,
WithPipelineInput("test"),
)
if err == nil || !strings.Contains(err.Error(), "user name is required") {
t.Errorf("Se esperaba error por falta de userName: %v", err)
}
// Test sin input
_, err = syndicate2.ExecutePipeline(ctx,
WithPipelineUserName("user1"),
)
if err == nil || !strings.Contains(err.Error(), "input is required") {
t.Errorf("Se esperaba error por falta de input: %v", err)
}
}
// TestExecutePipeline_WithImages verifica que las imágenes solo se pasen al primer agente.
func TestExecutePipeline_WithImages(t *testing.T) {
agent1 := newSyndicateTestAgent("agent1", "->A")
agent2 := newSyndicateTestAgent("agent2", "->B")
syndicate, _ := NewSyndicate(
WithAgents(agent1, agent2),
WithPipeline("agent1", "agent2"),
)
ctx := context.Background()
_, err := syndicate.ExecutePipeline(ctx,
WithPipelineUserName("user1"),
WithPipelineInput("test images"),
WithPipelineImages("https://example.com/image.jpg"),
)
if err != nil {
t.Errorf("Error en pipeline con imágenes: %v", err)
}
}
// TestGetAgentNames verifica que retorne todos los nombres de agentes.
func TestGetAgentNames(t *testing.T) {
agent1 := newSyndicateTestAgent("agent1", "->A")
agent2 := newSyndicateTestAgent("agent2", "->B")
syndicate, _ := NewSyndicate(WithAgents(agent1, agent2))
names := syndicate.GetAgentNames()
if len(names) != 2 {
t.Errorf("Se esperaban 2 nombres, se obtuvieron %d", len(names))
}
// Verificar que ambos nombres estén presentes
found1, found2 := false, false
for _, name := range names {
if name == "agent1" {
found1 = true
}
if name == "agent2" {
found2 = true
}
}
if !found1 || !found2 {
t.Errorf("No se encontraron todos los nombres de agentes: %v", names)
}
}
// TestExecuteAgentWithTimeout simula un timeout en la ejecución del agente.
func TestExecuteAgentWithTimeout(t *testing.T) {
// Crear un agente que demora en responder
slowAgent := &syndicateTestAgent{
name: "slowAgent",
chatFunc: func(ctx context.Context, options ...ChatOption) (string, error) {
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(100 * time.Millisecond):
return "slow response", nil
}
},
}
syndicate, _ := NewSyndicate(WithAgent(slowAgent))
// Crear un contexto que expira rápidamente
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, err := syndicate.ExecuteAgent(ctx, "slowAgent",
WithExecuteUserName("usuarioTimeout"),
WithExecuteInput("entrada"),
)
if err == nil {
t.Error("Se esperaba error por timeout, pero no ocurrió")
}
if !errors.Is(err, context.DeadlineExceeded) && !strings.Contains(err.Error(), "context deadline exceeded") {
t.Errorf("Se esperaba context.DeadlineExceeded, se obtuvo: %v", err)
}
}
// TestWithAgents verifica que WithAgents registre múltiples agentes.
func TestWithAgents(t *testing.T) {
agent1 := newSyndicateTestAgent("agent1", "->A")
agent2 := newSyndicateTestAgent("agent2", "->B")
agent3 := newSyndicateTestAgent("agent3", "->C")
syndicate, err := NewSyndicate(
WithAgents(agent1, agent2, agent3),
)
if err != nil {
t.Fatalf("Error creando syndicate: %v", err)
}
names := syndicate.GetAgentNames()
if len(names) != 3 {
t.Errorf("Se esperaban 3 agentes, se obtuvieron %d", len(names))
}
}