@weaviate/agents 0.0.0-stage → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +130 -2
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +1 -0
  5. package/dist/query/agent.d.ts +539 -0
  6. package/dist/query/agent.js +373 -0
  7. package/dist/query/agent.test.d.ts +1 -0
  8. package/dist/query/agent.test.js +1118 -0
  9. package/dist/query/collection.d.ts +22 -0
  10. package/dist/query/collection.js +12 -0
  11. package/dist/query/connection.d.ts +10 -0
  12. package/dist/query/connection.js +19 -0
  13. package/dist/query/filter.d.ts +2 -0
  14. package/dist/query/filter.js +20 -0
  15. package/dist/query/index.d.ts +4 -0
  16. package/dist/query/index.js +3 -0
  17. package/dist/query/media.d.ts +25 -0
  18. package/dist/query/media.js +24 -0
  19. package/dist/query/response/api-response-mapping.d.ts +3 -0
  20. package/dist/query/response/api-response-mapping.js +172 -0
  21. package/dist/query/response/api-response.d.ts +219 -0
  22. package/dist/query/response/api-response.js +1 -0
  23. package/dist/query/response/error.d.ts +6 -0
  24. package/dist/query/response/error.js +34 -0
  25. package/dist/query/response/index.d.ts +2 -0
  26. package/dist/query/response/index.js +2 -0
  27. package/dist/query/response/response-mapping.d.ts +23 -0
  28. package/dist/query/response/response-mapping.js +308 -0
  29. package/dist/query/response/response.d.ts +332 -0
  30. package/dist/query/response/response.js +44 -0
  31. package/dist/query/response/server-sent-events.d.ts +14 -0
  32. package/dist/query/response/server-sent-events.js +85 -0
  33. package/dist/query/search.d.ts +37 -0
  34. package/dist/query/search.js +87 -0
  35. package/package.json +46 -3
@@ -0,0 +1,1118 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { z } from "zod";
11
+ import { QueryAgent } from "./agent.js";
12
+ import { ComparisonOperator, } from "./response/response.js";
13
+ import { QueryAgentError } from "./response/error.js";
14
+ import { generatedImageWithOptions } from "./media.js";
15
+ it("runs the query agent", () => __awaiter(void 0, void 0, void 0, function* () {
16
+ const mockClient = {
17
+ getConnectionDetails: jest.fn().mockResolvedValue({
18
+ host: "test-cluster",
19
+ bearerToken: "test-token",
20
+ headers: { "X-Provider": "test-key" },
21
+ }),
22
+ };
23
+ global.fetch = jest.fn(() => Promise.resolve({
24
+ ok: true,
25
+ json: () => Promise.resolve({
26
+ original_query: "Test query",
27
+ collection_names: ["test-collection"],
28
+ searches: [
29
+ [
30
+ {
31
+ collection: "test-collection",
32
+ queries: ["Test search"],
33
+ filters: [],
34
+ filter_operators: "AND",
35
+ },
36
+ ],
37
+ ],
38
+ aggregations: [],
39
+ usage: {
40
+ requests: 1,
41
+ request_tokens: 128,
42
+ response_tokens: 256,
43
+ total_tokens: 384,
44
+ },
45
+ total_time: 10,
46
+ is_partial_answer: false,
47
+ missing_information: [],
48
+ final_answer: "Test answer",
49
+ sources: [
50
+ {
51
+ object_id: "123",
52
+ collection: "test-collection",
53
+ },
54
+ ],
55
+ }),
56
+ }));
57
+ const agent = new QueryAgent(mockClient, {
58
+ systemPrompt: "test system prompt",
59
+ });
60
+ const response = yield agent.run("What is the capital of France?", {
61
+ collections: ["test-collection"],
62
+ });
63
+ expect(response).toEqual({
64
+ outputType: "finalState",
65
+ originalQuery: "Test query",
66
+ collectionNames: ["test-collection"],
67
+ searches: [
68
+ [
69
+ {
70
+ collection: "test-collection",
71
+ queries: ["Test search"],
72
+ filters: [],
73
+ filterOperators: "AND",
74
+ },
75
+ ],
76
+ ],
77
+ aggregations: [],
78
+ usage: {
79
+ requests: 1,
80
+ requestTokens: 128,
81
+ responseTokens: 256,
82
+ totalTokens: 384,
83
+ details: undefined,
84
+ },
85
+ totalTime: 10,
86
+ isPartialAnswer: false,
87
+ missingInformation: [],
88
+ finalAnswer: "Test answer",
89
+ sources: [
90
+ {
91
+ objectId: "123",
92
+ collection: "test-collection",
93
+ },
94
+ ],
95
+ display: expect.any(Function),
96
+ });
97
+ }));
98
+ it("runs the query agent ask", () => __awaiter(void 0, void 0, void 0, function* () {
99
+ const mockClient = {
100
+ getConnectionDetails: jest.fn().mockResolvedValue({
101
+ host: "test-cluster",
102
+ bearerToken: "test-token",
103
+ headers: { "X-Provider": "test-key" },
104
+ }),
105
+ };
106
+ const apiSuccess = {
107
+ searches: [
108
+ {
109
+ query: "search query",
110
+ filters: {
111
+ filter_type: "integer",
112
+ property_name: "test_property",
113
+ operator: ComparisonOperator.GreaterThan,
114
+ value: 0,
115
+ },
116
+ collection: "test_collection",
117
+ sort_property: undefined,
118
+ uuid_value: undefined,
119
+ },
120
+ {
121
+ query: undefined,
122
+ filters: {
123
+ filter_type: "integer",
124
+ property_name: "test_property",
125
+ operator: ComparisonOperator.GreaterThan,
126
+ value: 0,
127
+ },
128
+ collection: "test_collection",
129
+ sort_property: {
130
+ property_name: "test_property",
131
+ order: "ascending",
132
+ tie_break: {
133
+ property_name: "test_property_2",
134
+ order: "descending",
135
+ tie_break: undefined,
136
+ },
137
+ },
138
+ uuid_value: "e6dc0a31-76f8-4bd3-b563-677ced6eb557",
139
+ },
140
+ ],
141
+ aggregations: [],
142
+ usage: {
143
+ model_units: 1,
144
+ usage_in_plan: true,
145
+ remaining_plan_requests: 2,
146
+ },
147
+ total_time: 1.5,
148
+ is_partial_answer: false,
149
+ missing_information: [],
150
+ final_answer: "Test answer",
151
+ sources: [
152
+ {
153
+ object_id: "123",
154
+ collection: "test-collection",
155
+ },
156
+ ],
157
+ };
158
+ global.fetch = jest.fn(() => Promise.resolve({
159
+ ok: true,
160
+ json: () => Promise.resolve(apiSuccess),
161
+ }));
162
+ const agent = new QueryAgent(mockClient, {
163
+ systemPrompt: "test system prompt",
164
+ });
165
+ const response = yield agent.ask("What is the capital of France?", {
166
+ collections: ["test-collection"],
167
+ });
168
+ expect(response).toEqual({
169
+ outputType: "finalState",
170
+ searches: [
171
+ {
172
+ collection: "test_collection",
173
+ query: "search query",
174
+ filters: {
175
+ filterType: "integer",
176
+ propertyName: "test_property",
177
+ operator: ComparisonOperator.GreaterThan,
178
+ value: 0,
179
+ },
180
+ sortProperty: undefined,
181
+ uuidValue: undefined,
182
+ },
183
+ {
184
+ collection: "test_collection",
185
+ query: undefined,
186
+ filters: {
187
+ filterType: "integer",
188
+ propertyName: "test_property",
189
+ operator: ComparisonOperator.GreaterThan,
190
+ value: 0,
191
+ },
192
+ sortProperty: {
193
+ propertyName: "test_property",
194
+ order: "ascending",
195
+ tieBreak: {
196
+ propertyName: "test_property_2",
197
+ order: "descending",
198
+ },
199
+ },
200
+ uuidValue: "e6dc0a31-76f8-4bd3-b563-677ced6eb557",
201
+ },
202
+ ],
203
+ aggregations: [],
204
+ usage: {
205
+ modelUnits: 1,
206
+ usageInPlan: true,
207
+ remainingPlanRequests: 2,
208
+ },
209
+ totalTime: 1.5,
210
+ isPartialAnswer: false,
211
+ missingInformation: [],
212
+ finalAnswer: "Test answer",
213
+ sources: [
214
+ {
215
+ objectId: "123",
216
+ collection: "test-collection",
217
+ },
218
+ ],
219
+ display: expect.any(Function),
220
+ });
221
+ }));
222
+ it("search-only mode success: caches searches and sends on subsequent request", () => __awaiter(void 0, void 0, void 0, function* () {
223
+ const mockClient = {
224
+ getConnectionDetails: jest.fn().mockResolvedValue({
225
+ host: "test-cluster",
226
+ bearerToken: "test-token",
227
+ headers: { "X-Provider": "test-key" },
228
+ }),
229
+ };
230
+ const capturedBodies = [];
231
+ const apiSuccess = {
232
+ searches: [
233
+ {
234
+ query: "search query",
235
+ filters: {
236
+ filter_type: "integer",
237
+ property_name: "test_property",
238
+ operator: ComparisonOperator.GreaterThan,
239
+ value: 0,
240
+ },
241
+ collection: "test_collection",
242
+ sort_property: undefined,
243
+ uuid_value: undefined,
244
+ },
245
+ {
246
+ query: undefined,
247
+ filters: {
248
+ filter_type: "integer",
249
+ property_name: "test_property",
250
+ operator: ComparisonOperator.GreaterThan,
251
+ value: 0,
252
+ },
253
+ collection: "test_collection",
254
+ sort_property: {
255
+ property_name: "test_property",
256
+ order: "ascending",
257
+ tie_break: {
258
+ property_name: "test_property_2",
259
+ order: "descending",
260
+ tie_break: undefined,
261
+ },
262
+ },
263
+ uuid_value: undefined,
264
+ },
265
+ ],
266
+ usage: {
267
+ model_units: 1,
268
+ usage_in_plan: true,
269
+ remaining_plan_requests: 2,
270
+ },
271
+ total_time: 1.5,
272
+ search_results: {
273
+ objects: [
274
+ {
275
+ uuid: "e6dc0a31-76f8-4bd3-b563-677ced6eb557",
276
+ metadata: {
277
+ creation_time: null,
278
+ update_time: null,
279
+ distance: null,
280
+ certainty: null,
281
+ score: 0.8,
282
+ explain_score: null,
283
+ rerank_score: null,
284
+ is_consistent: null,
285
+ },
286
+ references: null,
287
+ vector: {},
288
+ properties: {
289
+ test_property: 1.0,
290
+ text: "hello",
291
+ },
292
+ collection: "test_collection",
293
+ },
294
+ {
295
+ uuid: "cf5401cc-f4f1-4eb9-a6a1-173d34f94339",
296
+ metadata: {
297
+ creation_time: null,
298
+ update_time: null,
299
+ distance: null,
300
+ certainty: null,
301
+ score: 0.5,
302
+ explain_score: null,
303
+ rerank_score: null,
304
+ is_consistent: null,
305
+ },
306
+ references: null,
307
+ vector: {},
308
+ properties: {
309
+ test_property: 2.0,
310
+ text: "world!",
311
+ },
312
+ collection: "test_collection",
313
+ },
314
+ ],
315
+ },
316
+ };
317
+ // Mock the API response, and capture the request body to assert later
318
+ global.fetch = jest.fn((url, init) => {
319
+ if (init && init.body) {
320
+ capturedBodies.push(JSON.parse(init.body));
321
+ }
322
+ return Promise.resolve({
323
+ ok: true,
324
+ json: () => Promise.resolve(apiSuccess),
325
+ });
326
+ });
327
+ const agent = new QueryAgent(mockClient);
328
+ const first = yield agent.search("test query", {
329
+ limit: 2,
330
+ collections: ["test_collection"],
331
+ });
332
+ expect(first).toMatchObject({
333
+ searches: [
334
+ {
335
+ collection: "test_collection",
336
+ query: "search query",
337
+ filters: {
338
+ filterType: "integer",
339
+ propertyName: "test_property",
340
+ operator: ComparisonOperator.GreaterThan,
341
+ value: 0,
342
+ },
343
+ sortProperty: undefined,
344
+ uuidValue: undefined,
345
+ },
346
+ {
347
+ collection: "test_collection",
348
+ query: undefined,
349
+ filters: {
350
+ filterType: "integer",
351
+ propertyName: "test_property",
352
+ operator: ComparisonOperator.GreaterThan,
353
+ value: 0,
354
+ },
355
+ sortProperty: {
356
+ propertyName: "test_property",
357
+ order: "ascending",
358
+ tieBreak: {
359
+ propertyName: "test_property_2",
360
+ order: "descending",
361
+ },
362
+ },
363
+ uuidValue: undefined,
364
+ },
365
+ ],
366
+ usage: {
367
+ modelUnits: 1,
368
+ usageInPlan: true,
369
+ remainingPlanRequests: 2,
370
+ },
371
+ totalTime: 1.5,
372
+ searchResults: {
373
+ objects: [
374
+ {
375
+ uuid: "e6dc0a31-76f8-4bd3-b563-677ced6eb557",
376
+ metadata: {
377
+ score: 0.8,
378
+ },
379
+ vectors: {},
380
+ properties: {
381
+ test_property: 1.0,
382
+ text: "hello",
383
+ },
384
+ collection: "test_collection",
385
+ },
386
+ {
387
+ uuid: "cf5401cc-f4f1-4eb9-a6a1-173d34f94339",
388
+ metadata: {
389
+ score: 0.5,
390
+ },
391
+ vectors: {},
392
+ properties: {
393
+ test_property: 2.0,
394
+ text: "world!",
395
+ },
396
+ collection: "test_collection",
397
+ },
398
+ ],
399
+ },
400
+ });
401
+ expect(typeof first.next).toBe("function");
402
+ // First request should have searches: null (generation request)
403
+ expect(capturedBodies[0].searches).toBeNull();
404
+ // Second request uses the next method on the first response
405
+ const second = yield first.next({ limit: 2, offset: 1 });
406
+ // Second request should include the original searches (execution request)
407
+ expect(capturedBodies[1].searches).toEqual(apiSuccess.searches);
408
+ // Response mapping should be the same (because response is mocked)
409
+ expect(second).toMatchObject({
410
+ searches: first.searches,
411
+ usage: first.usage,
412
+ totalTime: first.totalTime,
413
+ searchResults: first.searchResults,
414
+ });
415
+ expect(typeof second.next).toBe("function");
416
+ }));
417
+ it("search-only mode sends diversity_weight when provided", () => __awaiter(void 0, void 0, void 0, function* () {
418
+ const mockClient = {
419
+ getConnectionDetails: jest.fn().mockResolvedValue({
420
+ host: "test-cluster",
421
+ bearerToken: "test-token",
422
+ headers: { "X-Provider": "test-key" },
423
+ }),
424
+ };
425
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
426
+ const capturedBodies = [];
427
+ const apiSuccess = {
428
+ searches: [
429
+ {
430
+ query: "search query",
431
+ collection: "test_collection",
432
+ },
433
+ ],
434
+ usage: {
435
+ model_units: 1,
436
+ usage_in_plan: true,
437
+ remaining_plan_requests: 2,
438
+ },
439
+ total_time: 1.0,
440
+ search_results: { objects: [] },
441
+ };
442
+ global.fetch = jest.fn((url, init) => {
443
+ if (init && init.body) {
444
+ capturedBodies.push(JSON.parse(init.body));
445
+ }
446
+ return Promise.resolve({
447
+ ok: true,
448
+ json: () => Promise.resolve(apiSuccess),
449
+ });
450
+ });
451
+ const agent = new QueryAgent(mockClient);
452
+ // With diversityWeight provided
453
+ const first = yield agent.search("test query", {
454
+ collections: ["test_collection"],
455
+ diversityWeight: 0.5,
456
+ });
457
+ expect(capturedBodies[0].diversity_weight).toBe(0.5);
458
+ // Paginated request should also include diversity_weight
459
+ yield first.next({ limit: 20, offset: 1 });
460
+ expect(capturedBodies[1].diversity_weight).toBe(0.5);
461
+ // Without diversityWeight provided
462
+ capturedBodies.length = 0;
463
+ yield agent.search("test query", {
464
+ collections: ["test_collection"],
465
+ });
466
+ expect(capturedBodies[0]).not.toHaveProperty("diversity_weight");
467
+ }));
468
+ it("search-only mode failure propagates QueryAgentError", () => __awaiter(void 0, void 0, void 0, function* () {
469
+ const mockClient = {
470
+ getConnectionDetails: jest.fn().mockResolvedValue({
471
+ host: "test-cluster",
472
+ bearerToken: "test-token",
473
+ headers: { "X-Provider": "test-key" },
474
+ }),
475
+ };
476
+ const errorJson = {
477
+ error: {
478
+ message: "Test error message",
479
+ code: "test_error_code",
480
+ details: { info: "test detail" },
481
+ },
482
+ };
483
+ global.fetch = jest.fn(() => Promise.resolve({
484
+ ok: false,
485
+ text: () => Promise.resolve(JSON.stringify(errorJson)),
486
+ }));
487
+ const agent = new QueryAgent(mockClient);
488
+ try {
489
+ yield agent.search("test query", {
490
+ limit: 2,
491
+ collections: ["test_collection"],
492
+ });
493
+ }
494
+ catch (err) {
495
+ expect(err).toBeInstanceOf(QueryAgentError);
496
+ expect(err).toMatchObject({
497
+ message: "Test error message",
498
+ code: "test_error_code",
499
+ details: { info: "test detail" },
500
+ });
501
+ }
502
+ }));
503
+ it("search-only mode sends filtering and persists through pagination", () => __awaiter(void 0, void 0, void 0, function* () {
504
+ const mockClient = {
505
+ getConnectionDetails: jest.fn().mockResolvedValue({
506
+ host: "test-cluster",
507
+ bearerToken: "test-token",
508
+ headers: { "X-Provider": "test-key" },
509
+ }),
510
+ };
511
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
512
+ const capturedBodies = [];
513
+ const apiSuccess = {
514
+ searches: [
515
+ {
516
+ query: "search query",
517
+ collection: "test_collection",
518
+ },
519
+ ],
520
+ usage: {
521
+ model_units: 1,
522
+ usage_in_plan: true,
523
+ remaining_plan_requests: 2,
524
+ },
525
+ total_time: 1.0,
526
+ search_results: { objects: [] },
527
+ };
528
+ global.fetch = jest.fn((url, init) => {
529
+ if (init && init.body) {
530
+ capturedBodies.push(JSON.parse(init.body));
531
+ }
532
+ return Promise.resolve({
533
+ ok: true,
534
+ json: () => Promise.resolve(apiSuccess),
535
+ });
536
+ });
537
+ const agent = new QueryAgent(mockClient);
538
+ const first = yield agent.search("test query", {
539
+ collections: ["test_collection"],
540
+ filtering: "precision",
541
+ });
542
+ // First request should include filtering
543
+ expect(capturedBodies[0].filtering).toBe("precision");
544
+ // Paginated request should also include filtering
545
+ yield first.next({ limit: 20, offset: 1 });
546
+ expect(capturedBodies[1].filtering).toBe("precision");
547
+ }));
548
+ it("search-only mode defaults filtering to recall", () => __awaiter(void 0, void 0, void 0, function* () {
549
+ const mockClient = {
550
+ getConnectionDetails: jest.fn().mockResolvedValue({
551
+ host: "test-cluster",
552
+ bearerToken: "test-token",
553
+ headers: { "X-Provider": "test-key" },
554
+ }),
555
+ };
556
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
557
+ const capturedBodies = [];
558
+ const apiSuccess = {
559
+ searches: [
560
+ {
561
+ query: "search query",
562
+ collection: "test_collection",
563
+ },
564
+ ],
565
+ usage: {
566
+ model_units: 1,
567
+ usage_in_plan: true,
568
+ remaining_plan_requests: 2,
569
+ },
570
+ total_time: 1.0,
571
+ search_results: { objects: [] },
572
+ };
573
+ global.fetch = jest.fn((url, init) => {
574
+ if (init && init.body) {
575
+ capturedBodies.push(JSON.parse(init.body));
576
+ }
577
+ return Promise.resolve({
578
+ ok: true,
579
+ json: () => Promise.resolve(apiSuccess),
580
+ });
581
+ });
582
+ const agent = new QueryAgent(mockClient);
583
+ yield agent.search("test query", {
584
+ collections: ["test_collection"],
585
+ });
586
+ // When no filtering is specified, it should not be sent (server-side default)
587
+ expect(capturedBodies[0].filtering).toBeUndefined();
588
+ }));
589
+ it("search-only mode sends effort and persists through pagination", () => __awaiter(void 0, void 0, void 0, function* () {
590
+ const mockClient = {
591
+ getConnectionDetails: jest.fn().mockResolvedValue({
592
+ host: "test-cluster",
593
+ bearerToken: "test-token",
594
+ headers: { "X-Provider": "test-key" },
595
+ }),
596
+ };
597
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
598
+ const capturedBodies = [];
599
+ const apiSuccess = {
600
+ searches: [
601
+ {
602
+ query: "search query",
603
+ collection: "test_collection",
604
+ },
605
+ ],
606
+ usage: {
607
+ model_units: 1,
608
+ usage_in_plan: true,
609
+ remaining_plan_requests: 2,
610
+ },
611
+ total_time: 1.0,
612
+ search_results: { objects: [] },
613
+ };
614
+ global.fetch = jest.fn((url, init) => {
615
+ if (init && init.body) {
616
+ capturedBodies.push(JSON.parse(init.body));
617
+ }
618
+ return Promise.resolve({
619
+ ok: true,
620
+ json: () => Promise.resolve(apiSuccess),
621
+ });
622
+ });
623
+ const agent = new QueryAgent(mockClient);
624
+ const first = yield agent.search("test query", {
625
+ collections: ["test_collection"],
626
+ effort: "ultrahigh",
627
+ });
628
+ // First request should include effort
629
+ expect(capturedBodies[0].effort).toBe("ultrahigh");
630
+ // Paginated request should also include effort
631
+ yield first.next({ limit: 20, offset: 1 });
632
+ expect(capturedBodies[1].effort).toBe("ultrahigh");
633
+ }));
634
+ it("search-only mode omits effort when not provided", () => __awaiter(void 0, void 0, void 0, function* () {
635
+ const mockClient = {
636
+ getConnectionDetails: jest.fn().mockResolvedValue({
637
+ host: "test-cluster",
638
+ bearerToken: "test-token",
639
+ headers: { "X-Provider": "test-key" },
640
+ }),
641
+ };
642
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
643
+ const capturedBodies = [];
644
+ const apiSuccess = {
645
+ searches: [
646
+ {
647
+ query: "search query",
648
+ collection: "test_collection",
649
+ },
650
+ ],
651
+ usage: {
652
+ model_units: 1,
653
+ usage_in_plan: true,
654
+ remaining_plan_requests: 2,
655
+ },
656
+ total_time: 1.0,
657
+ search_results: { objects: [] },
658
+ };
659
+ global.fetch = jest.fn((url, init) => {
660
+ if (init && init.body) {
661
+ capturedBodies.push(JSON.parse(init.body));
662
+ }
663
+ return Promise.resolve({
664
+ ok: true,
665
+ json: () => Promise.resolve(apiSuccess),
666
+ });
667
+ });
668
+ const agent = new QueryAgent(mockClient);
669
+ yield agent.search("test query", {
670
+ collections: ["test_collection"],
671
+ });
672
+ // When no effort is specified, it should not be sent (server-side default)
673
+ expect(capturedBodies[0].effort).toBeUndefined();
674
+ }));
675
+ it("search-only mode caches empty searches array for precision mode pagination", () => __awaiter(void 0, void 0, void 0, function* () {
676
+ const mockClient = {
677
+ getConnectionDetails: jest.fn().mockResolvedValue({
678
+ host: "test-cluster",
679
+ bearerToken: "test-token",
680
+ headers: { "X-Provider": "test-key" },
681
+ }),
682
+ };
683
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
684
+ const capturedBodies = [];
685
+ // Precision mode can return an empty searches array
686
+ const apiSuccess = {
687
+ searches: [],
688
+ usage: {
689
+ model_units: 1,
690
+ usage_in_plan: true,
691
+ remaining_plan_requests: 2,
692
+ },
693
+ total_time: 1.0,
694
+ search_results: { objects: [] },
695
+ };
696
+ global.fetch = jest.fn((url, init) => {
697
+ if (init && init.body) {
698
+ capturedBodies.push(JSON.parse(init.body));
699
+ }
700
+ return Promise.resolve({
701
+ ok: true,
702
+ json: () => Promise.resolve(apiSuccess),
703
+ });
704
+ });
705
+ const agent = new QueryAgent(mockClient);
706
+ const first = yield agent.search("test query", {
707
+ collections: ["test_collection"],
708
+ filtering: "precision",
709
+ });
710
+ // First request should have searches: null (generation request)
711
+ expect(capturedBodies[0].searches).toBeNull();
712
+ expect(capturedBodies[0].system_prompt).not.toBeUndefined();
713
+ // Second request should use the cached empty array, not re-send as generation request
714
+ yield first.next({ limit: 20, offset: 1 });
715
+ expect(capturedBodies[1].searches).toEqual([]);
716
+ // Should NOT have system_prompt — that's only on the initial generation request
717
+ expect(capturedBodies[1].system_prompt).toBeUndefined();
718
+ }));
719
+ it("suggest queries mode success", () => __awaiter(void 0, void 0, void 0, function* () {
720
+ const mockClient = {
721
+ getConnectionDetails: jest.fn().mockResolvedValue({
722
+ host: "test-cluster",
723
+ bearerToken: "test-token",
724
+ headers: { "X-Provider": "test-key" },
725
+ }),
726
+ };
727
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
728
+ const capturedBodies = [];
729
+ const apiSuccess = {
730
+ queries: [
731
+ { query: "What are the most popular items?" },
732
+ { query: "How many records exist?" },
733
+ { query: "Show me recent entries" },
734
+ ],
735
+ collection_count: 1,
736
+ usage: {
737
+ model_units: 1,
738
+ usage_in_plan: true,
739
+ remaining_plan_requests: 10,
740
+ },
741
+ total_time: 0.5,
742
+ };
743
+ global.fetch = jest.fn((url, init) => {
744
+ if (init && init.body) {
745
+ capturedBodies.push(JSON.parse(init.body));
746
+ }
747
+ return Promise.resolve({
748
+ ok: true,
749
+ json: () => Promise.resolve(apiSuccess),
750
+ });
751
+ });
752
+ const agent = new QueryAgent(mockClient);
753
+ const response = yield agent.suggestQueries({
754
+ collections: ["test_collection"],
755
+ });
756
+ expect(response).toEqual({
757
+ queries: [
758
+ { query: "What are the most popular items?" },
759
+ { query: "How many records exist?" },
760
+ { query: "Show me recent entries" },
761
+ ],
762
+ collectionCount: 1,
763
+ usage: {
764
+ modelUnits: 1,
765
+ usageInPlan: true,
766
+ remainingPlanRequests: 10,
767
+ },
768
+ totalTime: 0.5,
769
+ });
770
+ expect(capturedBodies[0].collections).toEqual(["test_collection"]);
771
+ expect(capturedBodies[0].num_queries).toBe(3);
772
+ expect(capturedBodies[0].instructions).toBeUndefined();
773
+ }));
774
+ it("suggest queries mode passes custom num_queries and instructions", () => __awaiter(void 0, void 0, void 0, function* () {
775
+ const mockClient = {
776
+ getConnectionDetails: jest.fn().mockResolvedValue({
777
+ host: "test-cluster",
778
+ bearerToken: "test-token",
779
+ headers: { "X-Provider": "test-key" },
780
+ }),
781
+ };
782
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
783
+ const capturedBodies = [];
784
+ const apiSuccess = {
785
+ queries: [
786
+ { query: "First query" },
787
+ { query: "Second query" },
788
+ { query: "Third query" },
789
+ { query: "Fourth query" },
790
+ { query: "Fifth query" },
791
+ ],
792
+ collection_count: 1,
793
+ usage: {
794
+ model_units: 1,
795
+ usage_in_plan: true,
796
+ remaining_plan_requests: 9,
797
+ },
798
+ total_time: 0.8,
799
+ };
800
+ global.fetch = jest.fn((url, init) => {
801
+ if (init && init.body) {
802
+ capturedBodies.push(JSON.parse(init.body));
803
+ }
804
+ return Promise.resolve({
805
+ ok: true,
806
+ json: () => Promise.resolve(apiSuccess),
807
+ });
808
+ });
809
+ const agent = new QueryAgent(mockClient);
810
+ yield agent.suggestQueries({
811
+ collections: ["test_collection"],
812
+ numQueries: 5,
813
+ instructions: "Focus on aggregation queries",
814
+ });
815
+ expect(capturedBodies[0].num_queries).toBe(5);
816
+ expect(capturedBodies[0].instructions).toBe("Focus on aggregation queries");
817
+ }));
818
+ it("suggest queries mode uses constructor collections", () => __awaiter(void 0, void 0, void 0, function* () {
819
+ const mockClient = {
820
+ getConnectionDetails: jest.fn().mockResolvedValue({
821
+ host: "test-cluster",
822
+ bearerToken: "test-token",
823
+ headers: { "X-Provider": "test-key" },
824
+ }),
825
+ };
826
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
827
+ const capturedBodies = [];
828
+ const apiSuccess = {
829
+ queries: [{ query: "Test query" }],
830
+ collection_count: 2,
831
+ usage: {
832
+ model_units: 1,
833
+ usage_in_plan: true,
834
+ remaining_plan_requests: 8,
835
+ },
836
+ total_time: 0.3,
837
+ };
838
+ global.fetch = jest.fn((url, init) => {
839
+ if (init && init.body) {
840
+ capturedBodies.push(JSON.parse(init.body));
841
+ }
842
+ return Promise.resolve({
843
+ ok: true,
844
+ json: () => Promise.resolve(apiSuccess),
845
+ });
846
+ });
847
+ const agent = new QueryAgent(mockClient, {
848
+ collections: ["collection_a", "collection_b"],
849
+ });
850
+ yield agent.suggestQueries();
851
+ expect(capturedBodies[0].collections).toEqual([
852
+ "collection_a",
853
+ "collection_b",
854
+ ]);
855
+ }));
856
+ it("suggest queries mode failure propagates QueryAgentError", () => __awaiter(void 0, void 0, void 0, function* () {
857
+ const mockClient = {
858
+ getConnectionDetails: jest.fn().mockResolvedValue({
859
+ host: "test-cluster",
860
+ bearerToken: "test-token",
861
+ headers: { "X-Provider": "test-key" },
862
+ }),
863
+ };
864
+ const errorJson = {
865
+ error: {
866
+ message: "Suggest queries failed",
867
+ code: "suggest_error",
868
+ details: { info: "bad request" },
869
+ },
870
+ };
871
+ global.fetch = jest.fn(() => Promise.resolve({
872
+ ok: false,
873
+ text: () => Promise.resolve(JSON.stringify(errorJson)),
874
+ }));
875
+ const agent = new QueryAgent(mockClient);
876
+ try {
877
+ yield agent.suggestQueries({
878
+ collections: ["test_collection"],
879
+ });
880
+ }
881
+ catch (err) {
882
+ expect(err).toBeInstanceOf(QueryAgentError);
883
+ expect(err).toMatchObject({
884
+ message: "Suggest queries failed",
885
+ code: "suggest_error",
886
+ details: { info: "bad request" },
887
+ });
888
+ }
889
+ }));
890
+ it("suggest queries with conversation includes conversation_context in request body", () => __awaiter(void 0, void 0, void 0, function* () {
891
+ const mockClient = {
892
+ getConnectionDetails: jest.fn().mockResolvedValue({
893
+ host: "test-cluster",
894
+ bearerToken: "test-token",
895
+ headers: { "X-Provider": "test-key" },
896
+ }),
897
+ };
898
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
899
+ const capturedBodies = [];
900
+ const apiSuccess = {
901
+ queries: [{ query: "Follow-up question?" }],
902
+ collection_count: 1,
903
+ usage: {
904
+ model_units: 1,
905
+ usage_in_plan: true,
906
+ remaining_plan_requests: 10,
907
+ },
908
+ total_time: 0.3,
909
+ };
910
+ global.fetch = jest.fn((url, init) => {
911
+ if (init && init.body) {
912
+ capturedBodies.push(JSON.parse(init.body));
913
+ }
914
+ return Promise.resolve({
915
+ ok: true,
916
+ json: () => Promise.resolve(apiSuccess),
917
+ });
918
+ });
919
+ const agent = new QueryAgent(mockClient);
920
+ const conversation = [
921
+ { role: "user", content: "What topics are covered?" },
922
+ {
923
+ role: "assistant",
924
+ content: "The collection covers ML and economics.",
925
+ },
926
+ ];
927
+ yield agent.suggestQueries({
928
+ collections: ["test_collection"],
929
+ conversation,
930
+ });
931
+ expect(capturedBodies[0].conversation_context).toEqual({
932
+ messages: conversation,
933
+ });
934
+ }));
935
+ it("suggest queries without conversation omits conversation_context from request body", () => __awaiter(void 0, void 0, void 0, function* () {
936
+ const mockClient = {
937
+ getConnectionDetails: jest.fn().mockResolvedValue({
938
+ host: "test-cluster",
939
+ bearerToken: "test-token",
940
+ headers: { "X-Provider": "test-key" },
941
+ }),
942
+ };
943
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
944
+ const capturedBodies = [];
945
+ const apiSuccess = {
946
+ queries: [{ query: "Some query?" }],
947
+ collection_count: 1,
948
+ usage: {
949
+ model_units: 1,
950
+ usage_in_plan: true,
951
+ remaining_plan_requests: 10,
952
+ },
953
+ total_time: 0.2,
954
+ };
955
+ global.fetch = jest.fn((url, init) => {
956
+ if (init && init.body) {
957
+ capturedBodies.push(JSON.parse(init.body));
958
+ }
959
+ return Promise.resolve({
960
+ ok: true,
961
+ json: () => Promise.resolve(apiSuccess),
962
+ });
963
+ });
964
+ const agent = new QueryAgent(mockClient);
965
+ yield agent.suggestQueries({
966
+ collections: ["test_collection"],
967
+ });
968
+ expect(capturedBodies[0].conversation_context).toBeUndefined();
969
+ }));
970
+ const mockClient = () => ({
971
+ getConnectionDetails: jest.fn().mockResolvedValue({
972
+ host: "test-cluster",
973
+ bearerToken: "test-token",
974
+ headers: { "X-Provider": "test-key" },
975
+ }),
976
+ });
977
+ const askApiResponse = (finalAnswer) => ({
978
+ searches: [],
979
+ aggregations: [],
980
+ usage: {
981
+ model_units: 1,
982
+ usage_in_plan: true,
983
+ remaining_plan_requests: 2,
984
+ },
985
+ total_time: 1.5,
986
+ is_partial_answer: false,
987
+ missing_information: [],
988
+ final_answer: finalAnswer,
989
+ sources: [],
990
+ });
991
+ it("ask with a Zod output format parses and validates the final answer", () => __awaiter(void 0, void 0, void 0, function* () {
992
+ const Answer = z.object({
993
+ answer: z.string(),
994
+ score: z.number(),
995
+ });
996
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
997
+ const capturedBodies = [];
998
+ const finalAnswer = JSON.stringify({ answer: "Paris", score: 0.9 });
999
+ global.fetch = jest.fn((url, init) => {
1000
+ if (init && init.body) {
1001
+ capturedBodies.push(JSON.parse(init.body));
1002
+ }
1003
+ return Promise.resolve({
1004
+ ok: true,
1005
+ json: () => Promise.resolve(askApiResponse(finalAnswer)),
1006
+ });
1007
+ });
1008
+ const agent = new QueryAgent(mockClient());
1009
+ const response = yield agent.ask("What is the capital of France?", {
1010
+ collections: ["test-collection"],
1011
+ outputFormat: Answer,
1012
+ });
1013
+ // The request carries the schema serialised to a Draft 2020-12 JSON Schema.
1014
+ expect(capturedBodies[0].output_format).toEqual(z.toJSONSchema(Answer, { target: "draft-2020-12" }));
1015
+ // The raw string is still available, plus the parsed (and validated) object.
1016
+ expect(response.finalAnswer).toBe(finalAnswer);
1017
+ expect(response.finalAnswerParsed).toEqual({ answer: "Paris", score: 0.9 });
1018
+ // Compile-time: the parsed type is inferred from the schema.
1019
+ const parsed = response;
1020
+ const score = parsed.finalAnswerParsed.score;
1021
+ expect(score).toBe(0.9);
1022
+ }));
1023
+ it("ask with a Zod output format throws when the answer violates the schema", () => __awaiter(void 0, void 0, void 0, function* () {
1024
+ const Answer = z.object({ answer: z.string(), score: z.number() });
1025
+ global.fetch = jest.fn(() => Promise.resolve({
1026
+ ok: true,
1027
+ // `score` is missing -> Zod validation must reject it.
1028
+ json: () => Promise.resolve(askApiResponse('{"answer":"Paris"}')),
1029
+ }));
1030
+ const agent = new QueryAgent(mockClient());
1031
+ yield expect(agent.ask("What is the capital of France?", {
1032
+ collections: ["test-collection"],
1033
+ outputFormat: Answer,
1034
+ })).rejects.toThrow();
1035
+ }));
1036
+ it("ask with a raw JSON Schema output format parses the final answer as JSON", () => __awaiter(void 0, void 0, void 0, function* () {
1037
+ const jsonSchema = {
1038
+ type: "object",
1039
+ properties: { answer: { type: "string" } },
1040
+ required: ["answer"],
1041
+ additionalProperties: false,
1042
+ };
1043
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1044
+ const capturedBodies = [];
1045
+ const finalAnswer = JSON.stringify({ answer: "Paris" });
1046
+ global.fetch = jest.fn((url, init) => {
1047
+ if (init && init.body) {
1048
+ capturedBodies.push(JSON.parse(init.body));
1049
+ }
1050
+ return Promise.resolve({
1051
+ ok: true,
1052
+ json: () => Promise.resolve(askApiResponse(finalAnswer)),
1053
+ });
1054
+ });
1055
+ const agent = new QueryAgent(mockClient());
1056
+ const response = yield agent.ask("What is the capital of France?", {
1057
+ collections: ["test-collection"],
1058
+ outputFormat: jsonSchema,
1059
+ });
1060
+ // A raw JSON Schema is forwarded verbatim.
1061
+ expect(capturedBodies[0].output_format).toEqual(jsonSchema);
1062
+ expect(response.finalAnswer).toBe(finalAnswer);
1063
+ expect(response.finalAnswerParsed).toEqual({ answer: "Paris" });
1064
+ }));
1065
+ it("ask with an image output format hides base64 from the schema and parses the image", () => __awaiter(void 0, void 0, void 0, function* () {
1066
+ const Answer = z.object({
1067
+ answer: z.string(),
1068
+ image: generatedImageWithOptions({ shape: "square" }).describe("An advert"),
1069
+ });
1070
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1071
+ const capturedBodies = [];
1072
+ const image = { image_prompt: "a red shoe", base64: "QUJD" };
1073
+ const finalAnswer = JSON.stringify({ answer: "A shoe", image });
1074
+ global.fetch = jest.fn((url, init) => {
1075
+ if (init && init.body) {
1076
+ capturedBodies.push(JSON.parse(init.body));
1077
+ }
1078
+ return Promise.resolve({
1079
+ ok: true,
1080
+ json: () => Promise.resolve(askApiResponse(finalAnswer)),
1081
+ });
1082
+ });
1083
+ const agent = new QueryAgent(mockClient());
1084
+ const response = yield agent.ask("Draw the best selling product", {
1085
+ collections: ["test-collection"],
1086
+ outputFormat: Answer,
1087
+ });
1088
+ // The image field is sent tagged, with its options and without base64, which the server fills.
1089
+ const imageSchema = capturedBodies[0].output_format.properties.image;
1090
+ expect(imageSchema["X-query-agent-image"]).toBe(true);
1091
+ expect(imageSchema["X-image-shape"]).toBe("square");
1092
+ expect(imageSchema.description).toBe("An advert");
1093
+ expect(imageSchema.properties).not.toHaveProperty("base64");
1094
+ expect(imageSchema.required).toEqual(["image_prompt"]);
1095
+ // The answer parses back into the image, base64 included.
1096
+ const parsedImage = response.finalAnswerParsed.image;
1097
+ expect(parsedImage).toEqual(image);
1098
+ }));
1099
+ it("ask without an output format omits output_format and returns plain text", () => __awaiter(void 0, void 0, void 0, function* () {
1100
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1101
+ const capturedBodies = [];
1102
+ global.fetch = jest.fn((url, init) => {
1103
+ if (init && init.body) {
1104
+ capturedBodies.push(JSON.parse(init.body));
1105
+ }
1106
+ return Promise.resolve({
1107
+ ok: true,
1108
+ json: () => Promise.resolve(askApiResponse("Plain text answer")),
1109
+ });
1110
+ });
1111
+ const agent = new QueryAgent(mockClient());
1112
+ const response = yield agent.ask("What is the capital of France?", {
1113
+ collections: ["test-collection"],
1114
+ });
1115
+ expect(capturedBodies[0].output_format).toBeUndefined();
1116
+ expect(response.finalAnswer).toBe("Plain text answer");
1117
+ expect("finalAnswerParsed" in response).toBe(false);
1118
+ }));