forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-agent.test.ts
More file actions
1698 lines (1448 loc) · 50.8 KB
/
Copy pathbasic-agent.test.ts
File metadata and controls
1698 lines (1448 loc) · 50.8 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
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { z } from "zod";
import { BasicAgent, defineTool, type ToolDefinition } from "../index";
import {
EventType,
type BaseEvent,
type ReasoningStartEvent,
type RunAgentInput,
} from "@ag-ui/client";
import { streamText } from "ai";
import {
mockStreamTextResponse,
textStart,
textDelta,
finish,
abort,
error,
collectEvents,
toolCallStreamingStart,
toolCallDelta,
toolCall,
toolResult,
reasoningStart,
reasoningDelta,
reasoningEnd,
} from "./test-helpers";
// Mock the ai module
vi.mock("ai", () => ({
streamText: vi.fn(),
tool: vi.fn((config) => config),
}));
// Mock the SDK clients
vi.mock("@ai-sdk/openai", () => ({
createOpenAI: vi.fn(() => (modelId: string) => ({
modelId,
provider: "openai",
})),
}));
vi.mock("@ai-sdk/anthropic", () => ({
createAnthropic: vi.fn(() => (modelId: string) => ({
modelId,
provider: "anthropic",
})),
}));
vi.mock("@ai-sdk/google", () => ({
createGoogleGenerativeAI: vi.fn(() => (modelId: string) => ({
modelId,
provider: "google",
})),
}));
describe("BasicAgent", () => {
const originalEnv = process.env;
beforeEach(() => {
vi.clearAllMocks();
process.env = { ...originalEnv };
process.env.OPENAI_API_KEY = "test-key";
process.env.ANTHROPIC_API_KEY = "test-key";
process.env.GOOGLE_API_KEY = "test-key";
});
afterEach(() => {
process.env = originalEnv;
});
describe("Basic Event Emission", () => {
it("should emit RUN_STARTED and RUN_FINISHED events", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([textDelta("Hello"), finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
expect(events[0]).toMatchObject({
type: EventType.RUN_STARTED,
threadId: "thread1",
runId: "run1",
});
expect(events[events.length - 1]).toMatchObject({
type: EventType.RUN_FINISHED,
threadId: "thread1",
runId: "run1",
});
});
it("should emit TEXT_MESSAGE_CHUNK events for text deltas", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
textDelta("Hello"),
textDelta(" world"),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
const textEvents = events.filter(
(e: any) => e.type === EventType.TEXT_MESSAGE_CHUNK,
);
expect(textEvents).toHaveLength(2);
expect(textEvents[0]).toMatchObject({
type: EventType.TEXT_MESSAGE_CHUNK,
role: "assistant",
delta: "Hello",
});
expect(textEvents[1]).toMatchObject({
type: EventType.TEXT_MESSAGE_CHUNK,
delta: " world",
});
});
it("should generate unique messageId when provider returns id '0'", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
textStart("0"), // Simulate Google Gemini returning "0"
textDelta("First message"),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
const textEvents = events.filter(
(e: any) => e.type === EventType.TEXT_MESSAGE_CHUNK,
);
expect(textEvents).toHaveLength(1);
// Verify that messageId is NOT "0" - should be a UUID
expect(textEvents[0].messageId).not.toBe("0");
expect(textEvents[0].messageId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
);
});
it("should use provider-supplied messageId when it's not '0'", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
const validId = "msg_abc123";
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
textStart(validId), // Valid ID from provider
textDelta("Test message"),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
const textEvents = events.filter(
(e: any) => e.type === EventType.TEXT_MESSAGE_CHUNK,
);
expect(textEvents).toHaveLength(1);
// Verify that the valid ID from provider is used
expect(textEvents[0].messageId).toBe(validId);
});
});
describe("Tool Call Events", () => {
it("should emit tool call lifecycle events", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
toolCallStreamingStart("call1", "testTool"),
toolCallDelta("call1", '{"arg'),
toolCallDelta("call1", '":"val"}'),
toolCall("call1", "testTool", { arg: "val" }),
toolResult("call1", "testTool", { result: "success" }),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
// Check for TOOL_CALL_START
const startEvent = events.find(
(e: any) => e.type === EventType.TOOL_CALL_START,
);
expect(startEvent).toMatchObject({
type: EventType.TOOL_CALL_START,
toolCallId: "call1",
toolCallName: "testTool",
});
// Check for TOOL_CALL_ARGS
const argsEvents = events.filter(
(e: any) => e.type === EventType.TOOL_CALL_ARGS,
);
expect(argsEvents).toHaveLength(2);
// Check for TOOL_CALL_END
const endEvent = events.find(
(e: any) => e.type === EventType.TOOL_CALL_END,
);
expect(endEvent).toMatchObject({
type: EventType.TOOL_CALL_END,
toolCallId: "call1",
});
// Check for TOOL_CALL_RESULT
const resultEvent = events.find(
(e: any) => e.type === EventType.TOOL_CALL_RESULT,
);
expect(resultEvent).toMatchObject({
type: EventType.TOOL_CALL_RESULT,
role: "tool",
toolCallId: "call1",
});
});
});
describe("Prompt Building", () => {
it("should not add system message when no prompt, context, or state", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [{ id: "1", role: "user", content: "Hello" }],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.messages).toHaveLength(1);
expect(callArgs.messages[0].role).toBe("user");
});
it("should prepend system message with config prompt", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful assistant.",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [{ id: "1", role: "user", content: "Hello" }],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.messages).toHaveLength(2);
expect(callArgs.messages[0]).toMatchObject({
role: "system",
content: "You are a helpful assistant.",
});
});
it("should include context in system message", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [
{ description: "User Name", value: "John Doe" },
{ description: "Location", value: "New York" },
],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
const systemMessage = callArgs.messages[0];
expect(systemMessage.role).toBe("system");
expect(systemMessage.content).toContain("Context from the application");
expect(systemMessage.content).toContain("User Name");
expect(systemMessage.content).toContain("John Doe");
expect(systemMessage.content).toContain("Location");
expect(systemMessage.content).toContain("New York");
});
it("should include state in system message", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: { counter: 0, items: ["a", "b"] },
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
const systemMessage = callArgs.messages[0];
expect(systemMessage.role).toBe("system");
expect(systemMessage.content).toContain("Application State");
expect(systemMessage.content).toContain("AGUISendStateSnapshot");
expect(systemMessage.content).toContain("AGUISendStateDelta");
expect(systemMessage.content).toContain('"counter": 0');
expect(systemMessage.content).toContain('"items"');
});
it("should combine prompt, context, and state", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
prompt: "You are helpful.",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [{ description: "Context", value: "Data" }],
state: { value: 1 },
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
const systemMessage = callArgs.messages[0];
expect(systemMessage.content).toContain("You are helpful.");
expect(systemMessage.content).toContain("Context from the application");
expect(systemMessage.content).toContain("Application State");
// Check order: prompt, then context, then state
const promptIndex = systemMessage.content.indexOf("You are helpful.");
const contextIndex = systemMessage.content.indexOf(
"Context from the application",
);
const stateIndex = systemMessage.content.indexOf("Application State");
expect(promptIndex).toBeLessThan(contextIndex);
expect(contextIndex).toBeLessThan(stateIndex);
});
});
describe("Forward System/Developer Messages", () => {
it("should ignore system messages by default", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "sys1", role: "system", content: "System instruction" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
// Should only have the user message, system message ignored
expect(callArgs.messages).toHaveLength(1);
expect(callArgs.messages[0].role).toBe("user");
});
it("should ignore developer messages by default", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "dev1", role: "developer", content: "Developer hint" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
// Should only have the user message, developer message ignored
expect(callArgs.messages).toHaveLength(1);
expect(callArgs.messages[0].role).toBe("user");
});
it("should forward system messages when forwardSystemMessages is true", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
forwardSystemMessages: true,
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "sys1", role: "system", content: "System instruction" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.messages).toHaveLength(2);
expect(callArgs.messages[0]).toMatchObject({
role: "system",
content: "System instruction",
});
expect(callArgs.messages[1].role).toBe("user");
});
it("should forward developer messages as system when forwardDeveloperMessages is true", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
forwardDeveloperMessages: true,
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "dev1", role: "developer", content: "Developer hint" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.messages).toHaveLength(2);
// Developer messages are converted to system role
expect(callArgs.messages[0]).toMatchObject({
role: "system",
content: "Developer hint",
});
expect(callArgs.messages[1].role).toBe("user");
});
it("should forward both system and developer messages when both flags are true", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
forwardSystemMessages: true,
forwardDeveloperMessages: true,
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "sys1", role: "system", content: "System instruction" },
{ id: "dev1", role: "developer", content: "Developer hint" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.messages).toHaveLength(3);
expect(callArgs.messages[0]).toMatchObject({
role: "system",
content: "System instruction",
});
expect(callArgs.messages[1]).toMatchObject({
role: "system",
content: "Developer hint",
});
expect(callArgs.messages[2].role).toBe("user");
});
it("should place config prompt before forwarded system/developer messages", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
prompt: "You are a helpful assistant.",
forwardSystemMessages: true,
forwardDeveloperMessages: true,
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [
{ id: "sys1", role: "system", content: "System instruction" },
{ id: "dev1", role: "developer", content: "Developer hint" },
{ id: "user1", role: "user", content: "Hello" },
],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
// Config prompt is prepended as first system message
expect(callArgs.messages).toHaveLength(4);
expect(callArgs.messages[0]).toMatchObject({
role: "system",
content: "You are a helpful assistant.",
});
expect(callArgs.messages[1]).toMatchObject({
role: "system",
content: "System instruction",
});
expect(callArgs.messages[2]).toMatchObject({
role: "system",
content: "Developer hint",
});
expect(callArgs.messages[3].role).toBe("user");
});
});
describe("Tool Configuration", () => {
it("should include tools from config", async () => {
const tool1 = defineTool({
name: "configTool",
description: "A config tool",
parameters: z.object({ input: z.string() }),
execute: async () => ({ result: "ok" }),
});
const agent = new BasicAgent({
model: "openai/gpt-4o",
tools: [tool1],
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.tools).toHaveProperty("configTool");
});
it("should merge config tools with input tools", async () => {
const configTool = defineTool({
name: "configTool",
description: "From config",
parameters: z.object({}),
execute: async () => ({ result: "ok" }),
});
const agent = new BasicAgent({
model: "openai/gpt-4o",
tools: [configTool],
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [
{
name: "inputTool",
description: "From input",
parameters: { type: "object", properties: {} },
},
],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.tools).toHaveProperty("configTool");
expect(callArgs.tools).toHaveProperty("inputTool");
});
it("should always include state update tools", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.tools).toHaveProperty("AGUISendStateSnapshot");
expect(callArgs.tools).toHaveProperty("AGUISendStateDelta");
});
});
describe("Property Overrides", () => {
it("should respect overridable properties", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
temperature: 0.5,
overridableProperties: ["temperature"],
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
forwardedProps: { temperature: 0.9 },
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.temperature).toBe(0.9);
});
it("should ignore non-overridable properties", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
temperature: 0.5,
overridableProperties: [], // No properties can be overridden
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([finish()]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
forwardedProps: { temperature: 0.9 },
};
await collectEvents(agent["run"](input));
const callArgs = vi.mocked(streamText).mock.calls[0][0];
expect(callArgs.temperature).toBe(0.5); // Original value, not overridden
});
});
describe("Error Handling", () => {
it("should emit RUN_ERROR event on failure", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockImplementation(() => {
throw new Error("Test error");
});
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
try {
await collectEvents(agent["run"](input));
expect.fail("Should have thrown");
} catch (error: any) {
// Error is expected - check that we got a RUN_ERROR event
// Note: The error is thrown after emitting the event
expect(error.message).toContain("Test error");
}
});
});
describe("Reasoning Event Emission", () => {
it("should emit full reasoning lifecycle events", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
reasoningStart(),
reasoningDelta("Let me think..."),
reasoningDelta(" about this."),
reasoningEnd(),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
// Verify event order
const eventTypes = events.map((e: any) => e.type);
expect(eventTypes[0]).toBe(EventType.RUN_STARTED);
const reasoningStartIdx = eventTypes.indexOf(EventType.REASONING_START);
const reasoningMsgStartIdx = eventTypes.indexOf(
EventType.REASONING_MESSAGE_START,
);
const reasoningContentIndices = eventTypes.reduce(
(acc: number[], type: string, idx: number) =>
type === EventType.REASONING_MESSAGE_CONTENT ? [...acc, idx] : acc,
[],
);
const reasoningMsgEndIdx = eventTypes.indexOf(
EventType.REASONING_MESSAGE_END,
);
const reasoningEndIdx = eventTypes.indexOf(EventType.REASONING_END);
expect(reasoningStartIdx).toBeGreaterThan(0);
expect(reasoningMsgStartIdx).toBeGreaterThan(reasoningStartIdx);
expect(reasoningContentIndices).toHaveLength(2);
expect(reasoningContentIndices[0]).toBeGreaterThan(reasoningMsgStartIdx);
expect(reasoningMsgEndIdx).toBeGreaterThan(
reasoningContentIndices[reasoningContentIndices.length - 1],
);
expect(reasoningEndIdx).toBeGreaterThan(reasoningMsgEndIdx);
// Verify consistent messageId across all reasoning events
const reasoningEvents = events.filter((e: any) =>
[
EventType.REASONING_START,
EventType.REASONING_MESSAGE_START,
EventType.REASONING_MESSAGE_CONTENT,
EventType.REASONING_MESSAGE_END,
EventType.REASONING_END,
].includes(e.type),
);
const messageIds = reasoningEvents.map((e: any) => e.messageId);
expect(new Set(messageIds).size).toBe(1);
// Verify REASONING_MESSAGE_START has role "reasoning"
const msgStartEvent = events.find(
(e: any) => e.type === EventType.REASONING_MESSAGE_START,
);
expect(msgStartEvent).toMatchObject({ role: "reasoning" });
// Verify content deltas
const contentEvents = events.filter(
(e: any) => e.type === EventType.REASONING_MESSAGE_CONTENT,
);
expect(contentEvents[0]).toMatchObject({ delta: "Let me think..." });
expect(contentEvents[1]).toMatchObject({ delta: " about this." });
// Verify last event is RUN_FINISHED
expect(eventTypes[eventTypes.length - 1]).toBe(EventType.RUN_FINISHED);
});
it("should emit reasoning events followed by text events", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
reasoningStart(),
reasoningDelta("thinking"),
reasoningEnd(),
textDelta("Hello"),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
const eventTypes = events.map((e: any) => e.type);
// Reasoning events should come before text events
const reasoningEndIdx = eventTypes.indexOf(EventType.REASONING_END);
const textChunkIdx = eventTypes.indexOf(EventType.TEXT_MESSAGE_CHUNK);
expect(reasoningEndIdx).toBeLessThan(textChunkIdx);
// Reasoning messageId should differ from text messageId
const reasoningEvent = events.find(
(e: any) => e.type === EventType.REASONING_START,
);
const textEvent = events.find(
(e: any) => e.type === EventType.TEXT_MESSAGE_CHUNK,
);
expect(reasoningEvent.messageId).not.toBe(textEvent.messageId);
});
it("should use provider-supplied reasoning id", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",
});
vi.mocked(streamText).mockReturnValue(
mockStreamTextResponse([
reasoningStart("reasoning-msg-123"),
reasoningDelta("content"),
reasoningEnd(),
finish(),
]) as any,
);
const input: RunAgentInput = {
threadId: "thread1",
runId: "run1",
messages: [],
tools: [],
context: [],
state: {},
};
const events = await collectEvents(agent["run"](input));
const reasoningEvents = events.filter((e: any) =>
[
EventType.REASONING_START,
EventType.REASONING_MESSAGE_START,
EventType.REASONING_MESSAGE_CONTENT,
EventType.REASONING_MESSAGE_END,
EventType.REASONING_END,
].includes(e.type),
);
for (const event of reasoningEvents) {
expect(event.messageId).toBe("reasoning-msg-123");
}
});
it("should generate unique reasoningMessageId when provider returns id '0'", async () => {
const agent = new BasicAgent({
model: "openai/gpt-4o",