@antfly/sdk 0.0.4 → 0.0.6

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.
package/dist/index.cjs CHANGED
@@ -31,7 +31,25 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  AntflyClient: () => AntflyClient,
34
- default: () => index_default
34
+ boolean: () => boolean,
35
+ conjunction: () => conjunction,
36
+ dateRange: () => dateRange,
37
+ default: () => index_default,
38
+ disjunction: () => disjunction,
39
+ docIds: () => docIds,
40
+ embedderProviders: () => embedderProviders,
41
+ fuzzy: () => fuzzy,
42
+ generatorProviders: () => generatorProviders,
43
+ geoBoundingBox: () => geoBoundingBox,
44
+ geoDistance: () => geoDistance,
45
+ match: () => match,
46
+ matchAll: () => matchAll,
47
+ matchNone: () => matchNone,
48
+ matchPhrase: () => matchPhrase,
49
+ numericRange: () => numericRange,
50
+ prefix: () => prefix,
51
+ queryString: () => queryString,
52
+ term: () => term
35
53
  });
36
54
  module.exports = __toCommonJS(index_exports);
37
55
 
@@ -46,8 +64,10 @@ var AntflyClient = class {
46
64
  /**
47
65
  * List all tables
48
66
  */
49
- list: async () => {
50
- const { data, error } = await this.client.GET("/table", {});
67
+ list: async (params) => {
68
+ const { data, error } = await this.client.GET("/tables", {
69
+ params: params ? { query: params } : void 0
70
+ });
51
71
  if (error) throw new Error(`Failed to list tables: ${error.error}`);
52
72
  return data;
53
73
  },
@@ -55,7 +75,7 @@ var AntflyClient = class {
55
75
  * Get table details and status
56
76
  */
57
77
  get: async (tableName) => {
58
- const { data, error } = await this.client.GET("/table/{tableName}", {
78
+ const { data, error } = await this.client.GET("/tables/{tableName}", {
59
79
  params: { path: { tableName } }
60
80
  });
61
81
  if (error) throw new Error(`Failed to get table: ${error.error}`);
@@ -65,7 +85,7 @@ var AntflyClient = class {
65
85
  * Create a new table
66
86
  */
67
87
  create: async (tableName, config = {}) => {
68
- const { data, error } = await this.client.POST("/table/{tableName}", {
88
+ const { data, error } = await this.client.POST("/tables/{tableName}", {
69
89
  params: { path: { tableName } },
70
90
  body: config
71
91
  });
@@ -76,28 +96,40 @@ var AntflyClient = class {
76
96
  * Drop a table
77
97
  */
78
98
  drop: async (tableName) => {
79
- const { error } = await this.client.DELETE("/table/{tableName}", {
99
+ const { error } = await this.client.DELETE("/tables/{tableName}", {
80
100
  params: { path: { tableName } }
81
101
  });
82
102
  if (error) throw new Error(`Failed to drop table: ${error.error}`);
83
103
  return true;
84
104
  },
85
105
  /**
86
- * Query a specific table
106
+ * Update schema for a table
87
107
  */
88
- query: async (tableName, request) => {
89
- const { data, error } = await this.client.POST("/table/{tableName}/query", {
108
+ updateSchema: async (tableName, config) => {
109
+ const { data, error } = await this.client.PUT("/tables/{tableName}/schema", {
90
110
  params: { path: { tableName } },
91
- body: request
111
+ body: config
92
112
  });
93
- if (error) throw new Error(`Table query failed: ${error.error}`);
113
+ if (error) throw new Error(`Failed to update table schema: ${error.error}`);
94
114
  return data;
95
115
  },
116
+ /**
117
+ * Query a specific table
118
+ */
119
+ query: async (tableName, request) => {
120
+ return this.performQuery("/tables/{tableName}/query", request, tableName);
121
+ },
122
+ /**
123
+ * Execute multiple queries on a specific table
124
+ */
125
+ multiquery: async (tableName, requests) => {
126
+ return this.performMultiquery("/tables/{tableName}/query", requests, tableName);
127
+ },
96
128
  /**
97
129
  * Perform batch operations on a table
98
130
  */
99
131
  batch: async (tableName, request) => {
100
- const { data, error } = await this.client.POST("/table/{tableName}/batch", {
132
+ const { data, error } = await this.client.POST("/tables/{tableName}/batch", {
101
133
  params: { path: { tableName } },
102
134
  // @ts-expect-error Our BatchRequest type allows any object shape for inserts
103
135
  body: request
@@ -109,7 +141,7 @@ var AntflyClient = class {
109
141
  * Backup a table
110
142
  */
111
143
  backup: async (tableName, request) => {
112
- const { data, error } = await this.client.POST("/table/{tableName}/backup", {
144
+ const { data, error } = await this.client.POST("/tables/{tableName}/backup", {
113
145
  params: { path: { tableName } },
114
146
  body: request
115
147
  });
@@ -120,7 +152,7 @@ var AntflyClient = class {
120
152
  * Restore a table from backup
121
153
  */
122
154
  restore: async (tableName, request) => {
123
- const { data, error } = await this.client.POST("/table/{tableName}/restore", {
155
+ const { data, error } = await this.client.POST("/tables/{tableName}/restore", {
124
156
  params: { path: { tableName } },
125
157
  body: request
126
158
  });
@@ -131,11 +163,21 @@ var AntflyClient = class {
131
163
  * Lookup a specific key in a table
132
164
  */
133
165
  lookup: async (tableName, key) => {
134
- const { data, error } = await this.client.GET("/table/{tableName}/key/{key}", {
166
+ const { data, error } = await this.client.GET("/tables/{tableName}/lookup/{key}", {
135
167
  params: { path: { tableName, key } }
136
168
  });
137
169
  if (error) throw new Error(`Key lookup failed: ${error.error}`);
138
170
  return data;
171
+ },
172
+ /**
173
+ * RAG (Retrieval-Augmented Generation) query on a specific table with streaming or citations
174
+ * @param tableName - Name of the table to query
175
+ * @param request - RAG request with query and summarizer config (set with_streaming: true to enable streaming)
176
+ * @param callbacks - Optional callbacks for structured SSE events (hit, summary, citation, done, error)
177
+ * @returns Promise with RAG result (JSON) or AbortController (when streaming)
178
+ */
179
+ rag: async (tableName, request, callbacks) => {
180
+ return this.performRag(`/tables/${tableName}/rag`, request, callbacks);
139
181
  }
140
182
  };
141
183
  /**
@@ -146,7 +188,7 @@ var AntflyClient = class {
146
188
  * List all indexes for a table
147
189
  */
148
190
  list: async (tableName) => {
149
- const { data, error } = await this.client.GET("/table/{tableName}/index", {
191
+ const { data, error } = await this.client.GET("/tables/{tableName}/indexes", {
150
192
  params: { path: { tableName } }
151
193
  });
152
194
  if (error) throw new Error(`Failed to list indexes: ${error.error}`);
@@ -156,7 +198,7 @@ var AntflyClient = class {
156
198
  * Get index details
157
199
  */
158
200
  get: async (tableName, indexName) => {
159
- const { data, error } = await this.client.GET("/table/{tableName}/index/{indexName}", {
201
+ const { data, error } = await this.client.GET("/tables/{tableName}/indexes/{indexName}", {
160
202
  params: { path: { tableName, indexName } }
161
203
  });
162
204
  if (error) throw new Error(`Failed to get index: ${error.error}`);
@@ -165,9 +207,9 @@ var AntflyClient = class {
165
207
  /**
166
208
  * Create a new index
167
209
  */
168
- create: async (tableName, indexName, config) => {
169
- const { error } = await this.client.POST("/table/{tableName}/index/{indexName}", {
170
- params: { path: { tableName, indexName } },
210
+ create: async (tableName, config) => {
211
+ const { error } = await this.client.POST("/tables/{tableName}/indexes/{indexName}", {
212
+ params: { path: { tableName, indexName: config.name } },
171
213
  body: config
172
214
  });
173
215
  if (error) throw new Error(`Failed to create index: ${error.error}`);
@@ -177,7 +219,7 @@ var AntflyClient = class {
177
219
  * Drop an index
178
220
  */
179
221
  drop: async (tableName, indexName) => {
180
- const { error } = await this.client.DELETE("/table/{tableName}/index/{indexName}", {
222
+ const { error } = await this.client.DELETE("/tables/{tableName}/indexes/{indexName}", {
181
223
  params: { path: { tableName, indexName } }
182
224
  });
183
225
  if (error) throw new Error(`Failed to drop index: ${error.error}`);
@@ -188,11 +230,27 @@ var AntflyClient = class {
188
230
  * User management operations
189
231
  */
190
232
  this.users = {
233
+ /**
234
+ * Get current authenticated user
235
+ */
236
+ getCurrentUser: async () => {
237
+ const { data, error } = await this.client.GET("/users/me");
238
+ if (error) throw new Error(`Failed to get current user: ${error.error}`);
239
+ return data;
240
+ },
241
+ /**
242
+ * List all users
243
+ */
244
+ list: async () => {
245
+ const { data, error } = await this.client.GET("/users");
246
+ if (error) throw new Error(`Failed to list users: ${error.error}`);
247
+ return data;
248
+ },
191
249
  /**
192
250
  * Get user details
193
251
  */
194
252
  get: async (userName) => {
195
- const { data, error } = await this.client.GET("/user/{userName}", {
253
+ const { data, error } = await this.client.GET("/users/{userName}", {
196
254
  params: { path: { userName } }
197
255
  });
198
256
  if (error) throw new Error(`Failed to get user: ${error.error}`);
@@ -202,7 +260,7 @@ var AntflyClient = class {
202
260
  * Create a new user
203
261
  */
204
262
  create: async (userName, request) => {
205
- const { data, error } = await this.client.POST("/user/{userName}", {
263
+ const { data, error } = await this.client.POST("/users/{userName}", {
206
264
  params: { path: { userName } },
207
265
  body: request
208
266
  });
@@ -213,7 +271,7 @@ var AntflyClient = class {
213
271
  * Delete a user
214
272
  */
215
273
  delete: async (userName) => {
216
- const { error } = await this.client.DELETE("/user/{userName}", {
274
+ const { error } = await this.client.DELETE("/users/{userName}", {
217
275
  params: { path: { userName } }
218
276
  });
219
277
  if (error) throw new Error(`Failed to delete user: ${error.error}`);
@@ -223,7 +281,7 @@ var AntflyClient = class {
223
281
  * Update user password
224
282
  */
225
283
  updatePassword: async (userName, newPassword) => {
226
- const { data, error } = await this.client.PUT("/user/{userName}/password", {
284
+ const { data, error } = await this.client.PUT("/users/{userName}/password", {
227
285
  params: { path: { userName } },
228
286
  body: { new_password: newPassword }
229
287
  });
@@ -234,7 +292,7 @@ var AntflyClient = class {
234
292
  * Get user permissions
235
293
  */
236
294
  getPermissions: async (userName) => {
237
- const { data, error } = await this.client.GET("/user/{userName}/permission", {
295
+ const { data, error } = await this.client.GET("/users/{userName}/permissions", {
238
296
  params: { path: { userName } }
239
297
  });
240
298
  if (error) throw new Error(`Failed to get permissions: ${error.error}`);
@@ -244,7 +302,7 @@ var AntflyClient = class {
244
302
  * Add permission to user
245
303
  */
246
304
  addPermission: async (userName, permission) => {
247
- const { data, error } = await this.client.POST("/user/{userName}/permission", {
305
+ const { data, error } = await this.client.POST("/users/{userName}/permissions", {
248
306
  params: { path: { userName } },
249
307
  body: permission
250
308
  });
@@ -255,7 +313,7 @@ var AntflyClient = class {
255
313
  * Remove permission from user
256
314
  */
257
315
  removePermission: async (userName, resource, resourceType) => {
258
- const { error } = await this.client.DELETE("/user/{userName}/permission", {
316
+ const { error } = await this.client.DELETE("/users/{userName}/permissions", {
259
317
  params: {
260
318
  path: { userName },
261
319
  query: { resource, resourceType }
@@ -276,7 +334,13 @@ var AntflyClient = class {
276
334
  }
277
335
  this.client = (0, import_openapi_fetch.default)({
278
336
  baseUrl: config.baseUrl,
279
- headers
337
+ headers,
338
+ bodySerializer: (body) => {
339
+ if (typeof body === "string") {
340
+ return body;
341
+ }
342
+ return JSON.stringify(body);
343
+ }
280
344
  });
281
345
  }
282
346
  /**
@@ -290,20 +354,500 @@ var AntflyClient = class {
290
354
  headers: {
291
355
  ...this.config.headers,
292
356
  Authorization: `Basic ${auth}`
357
+ },
358
+ bodySerializer: (body) => {
359
+ if (typeof body === "string") {
360
+ return body;
361
+ }
362
+ return JSON.stringify(body);
293
363
  }
294
364
  });
295
365
  }
366
+ /**
367
+ * Get cluster status
368
+ */
369
+ async getStatus() {
370
+ const { data, error } = await this.client.GET("/status");
371
+ if (error) throw new Error(`Failed to get status: ${error.error}`);
372
+ return data;
373
+ }
374
+ /**
375
+ * Private helper for query requests to avoid code duplication
376
+ */
377
+ async performQuery(path, request, tableName) {
378
+ if (path === "/tables/{tableName}/query" && tableName) {
379
+ const { data, error } = await this.client.POST("/tables/{tableName}/query", {
380
+ params: { path: { tableName } },
381
+ body: request
382
+ });
383
+ if (error) throw new Error(`Table query failed: ${error.error}`);
384
+ return data;
385
+ } else {
386
+ const { data, error } = await this.client.POST("/query", {
387
+ body: request
388
+ });
389
+ if (error) throw new Error(`Query failed: ${error.error}`);
390
+ return data;
391
+ }
392
+ }
393
+ /**
394
+ * Private helper for multiquery requests to avoid code duplication
395
+ */
396
+ async performMultiquery(path, requests, tableName) {
397
+ const ndjson = requests.map((request) => JSON.stringify(request)).join("\n") + "\n";
398
+ if (path === "/tables/{tableName}/query" && tableName) {
399
+ const { data, error } = await this.client.POST("/tables/{tableName}/query", {
400
+ params: { path: { tableName } },
401
+ body: ndjson,
402
+ headers: {
403
+ "Content-Type": "application/x-ndjson"
404
+ }
405
+ });
406
+ if (error) throw new Error(`Table multi-query failed: ${error.error}`);
407
+ return data;
408
+ } else {
409
+ const { data, error } = await this.client.POST("/query", {
410
+ body: ndjson,
411
+ headers: {
412
+ "Content-Type": "application/x-ndjson"
413
+ }
414
+ });
415
+ if (error) throw new Error(`Multi-query failed: ${error.error}`);
416
+ return data;
417
+ }
418
+ }
296
419
  /**
297
420
  * Global query operations
298
421
  */
299
422
  async query(request) {
300
- const { data, error } = await this.client.POST("/query", {
423
+ const data = await this.performQuery("/query", request);
424
+ return data?.responses?.[0];
425
+ }
426
+ /**
427
+ * Execute multiple queries in a single request
428
+ */
429
+ async multiquery(requests) {
430
+ return this.performMultiquery("/query", requests);
431
+ }
432
+ /**
433
+ * Private helper for RAG requests to avoid code duplication
434
+ */
435
+ async performRag(path, request, callbacks) {
436
+ const headers = {
437
+ "Content-Type": "application/json",
438
+ Accept: "text/event-stream, application/json"
439
+ };
440
+ if (this.config.auth) {
441
+ const auth = btoa(`${this.config.auth.username}:${this.config.auth.password}`);
442
+ headers["Authorization"] = `Basic ${auth}`;
443
+ }
444
+ Object.assign(headers, this.config.headers);
445
+ const abortController = new AbortController();
446
+ const response = await fetch(`${this.config.baseUrl}${path}`, {
447
+ method: "POST",
448
+ headers,
449
+ body: JSON.stringify(request),
450
+ signal: abortController.signal
451
+ });
452
+ if (!response.ok) {
453
+ const errorText = await response.text();
454
+ throw new Error(`RAG request failed: ${response.status} ${errorText}`);
455
+ }
456
+ if (!response.body) {
457
+ throw new Error("Response body is null");
458
+ }
459
+ const contentType = response.headers.get("content-type") || "";
460
+ const isJSON = contentType.includes("application/json");
461
+ if (isJSON) {
462
+ const ragResult = await response.json();
463
+ return ragResult;
464
+ }
465
+ if (callbacks) {
466
+ const reader = response.body.getReader();
467
+ const decoder = new TextDecoder();
468
+ let buffer = "";
469
+ let currentEvent = "";
470
+ (async () => {
471
+ try {
472
+ while (true) {
473
+ const { done, value } = await reader.read();
474
+ if (done) break;
475
+ buffer += decoder.decode(value, { stream: true });
476
+ const lines = buffer.split("\n");
477
+ buffer = lines.pop() || "";
478
+ for (const line of lines) {
479
+ if (!line.trim()) {
480
+ currentEvent = "";
481
+ continue;
482
+ }
483
+ if (line.startsWith("event: ")) {
484
+ currentEvent = line.slice(7).trim();
485
+ } else if (line.startsWith("data: ")) {
486
+ const data = line.slice(6).trim();
487
+ try {
488
+ switch (currentEvent) {
489
+ case "hits_start":
490
+ if (callbacks.onHitsStart) {
491
+ const hitsStartData = JSON.parse(data);
492
+ callbacks.onHitsStart(hitsStartData);
493
+ }
494
+ break;
495
+ case "hit":
496
+ if (callbacks.onHit) {
497
+ const hit = JSON.parse(data);
498
+ callbacks.onHit(hit);
499
+ }
500
+ break;
501
+ case "hits_end":
502
+ if (callbacks.onHitsEnd) {
503
+ const hitsEndData = JSON.parse(data);
504
+ callbacks.onHitsEnd(hitsEndData);
505
+ }
506
+ break;
507
+ case "table_result":
508
+ if (callbacks.onHit) {
509
+ const result = JSON.parse(data);
510
+ const hits = result?.hits?.hits || [];
511
+ hits.forEach((hit) => callbacks.onHit(hit));
512
+ }
513
+ break;
514
+ case "summary":
515
+ if (callbacks.onSummary) {
516
+ const chunk = JSON.parse(data);
517
+ callbacks.onSummary(chunk);
518
+ }
519
+ break;
520
+ case "done":
521
+ if (callbacks.onDone) {
522
+ const doneData = JSON.parse(data);
523
+ callbacks.onDone(doneData);
524
+ }
525
+ return;
526
+ case "error":
527
+ if (callbacks.onError) {
528
+ const error = JSON.parse(data);
529
+ callbacks.onError(error);
530
+ }
531
+ throw new Error(data);
532
+ }
533
+ } catch (e) {
534
+ console.warn("Failed to parse SSE data:", currentEvent, data, e);
535
+ }
536
+ }
537
+ }
538
+ }
539
+ } catch (error) {
540
+ if (error.name !== "AbortError") {
541
+ console.error("RAG streaming error:", error);
542
+ }
543
+ }
544
+ })();
545
+ }
546
+ return abortController;
547
+ }
548
+ /**
549
+ * Private helper for Answer Agent requests to avoid code duplication
550
+ */
551
+ async performAnswerAgent(path, request, callbacks) {
552
+ const headers = {
553
+ "Content-Type": "application/json",
554
+ Accept: "text/event-stream, application/json"
555
+ };
556
+ if (this.config.auth) {
557
+ const auth = btoa(`${this.config.auth.username}:${this.config.auth.password}`);
558
+ headers["Authorization"] = `Basic ${auth}`;
559
+ }
560
+ Object.assign(headers, this.config.headers);
561
+ const abortController = new AbortController();
562
+ const response = await fetch(`${this.config.baseUrl}${path}`, {
563
+ method: "POST",
564
+ headers,
565
+ body: JSON.stringify(request),
566
+ signal: abortController.signal
567
+ });
568
+ if (!response.ok) {
569
+ const errorText = await response.text();
570
+ throw new Error(`Answer agent request failed: ${response.status} ${errorText}`);
571
+ }
572
+ if (!response.body) {
573
+ throw new Error("Response body is null");
574
+ }
575
+ const contentType = response.headers.get("content-type") || "";
576
+ const isJSON = contentType.includes("application/json");
577
+ if (isJSON) {
578
+ const result = await response.json();
579
+ return result;
580
+ }
581
+ if (callbacks) {
582
+ const reader = response.body.getReader();
583
+ const decoder = new TextDecoder();
584
+ let buffer = "";
585
+ let currentEvent = "";
586
+ (async () => {
587
+ try {
588
+ while (true) {
589
+ const { done, value } = await reader.read();
590
+ if (done) break;
591
+ buffer += decoder.decode(value, { stream: true });
592
+ const lines = buffer.split("\n");
593
+ buffer = lines.pop() || "";
594
+ for (const line of lines) {
595
+ if (!line.trim()) {
596
+ currentEvent = "";
597
+ continue;
598
+ }
599
+ if (line.startsWith("event: ")) {
600
+ currentEvent = line.slice(7).trim();
601
+ } else if (line.startsWith("data: ")) {
602
+ const data = line.slice(6).trim();
603
+ try {
604
+ switch (currentEvent) {
605
+ case "classification":
606
+ if (callbacks.onClassification) {
607
+ const classData = JSON.parse(data);
608
+ callbacks.onClassification(classData);
609
+ }
610
+ break;
611
+ case "reasoning":
612
+ if (callbacks.onReasoning) {
613
+ callbacks.onReasoning(data);
614
+ }
615
+ break;
616
+ case "hits_start":
617
+ if (callbacks.onHitsStart) {
618
+ const hitsStartData = JSON.parse(data);
619
+ callbacks.onHitsStart(hitsStartData);
620
+ }
621
+ break;
622
+ case "hit":
623
+ if (callbacks.onHit) {
624
+ const hit = JSON.parse(data);
625
+ callbacks.onHit(hit);
626
+ }
627
+ break;
628
+ case "hits_end":
629
+ if (callbacks.onHitsEnd) {
630
+ const hitsEndData = JSON.parse(data);
631
+ callbacks.onHitsEnd(hitsEndData);
632
+ }
633
+ break;
634
+ case "answer":
635
+ if (callbacks.onAnswer) {
636
+ callbacks.onAnswer(data);
637
+ }
638
+ break;
639
+ case "confidence":
640
+ if (callbacks.onConfidence) {
641
+ const confidence = JSON.parse(data);
642
+ callbacks.onConfidence(confidence);
643
+ }
644
+ break;
645
+ case "followup_question":
646
+ if (callbacks.onFollowUpQuestion) {
647
+ callbacks.onFollowUpQuestion(data);
648
+ }
649
+ break;
650
+ case "done":
651
+ if (callbacks.onDone) {
652
+ const doneData = JSON.parse(data);
653
+ callbacks.onDone(doneData);
654
+ }
655
+ return;
656
+ case "error":
657
+ if (callbacks.onError) {
658
+ const error = JSON.parse(data);
659
+ callbacks.onError(error);
660
+ }
661
+ throw new Error(data);
662
+ }
663
+ } catch (e) {
664
+ console.warn("Failed to parse SSE data:", currentEvent, data, e);
665
+ }
666
+ }
667
+ }
668
+ }
669
+ } catch (error) {
670
+ if (error.name !== "AbortError") {
671
+ console.error("Answer agent streaming error:", error);
672
+ }
673
+ }
674
+ })();
675
+ }
676
+ return abortController;
677
+ }
678
+ /**
679
+ * RAG (Retrieval-Augmented Generation) query with streaming or citations
680
+ * @param request - RAG request with query and summarizer config (set with_streaming: true to enable streaming)
681
+ * @param callbacks - Optional callbacks for structured SSE events (hit, summary, citation, done, error)
682
+ * @returns Promise with RAG result (JSON) or AbortController (when streaming)
683
+ */
684
+ async rag(request, callbacks) {
685
+ return this.performRag("/rag", request, callbacks);
686
+ }
687
+ /**
688
+ * Answer Agent - Intelligent query routing and generation
689
+ * Automatically classifies queries, generates optimal searches, and provides answers
690
+ * @param request - Answer agent request with query and generator config
691
+ * @param callbacks - Optional callbacks for SSE events (classification, hits_start, hit, hits_end, reasoning, answer, followup_question, done, error)
692
+ * @returns Promise with AnswerAgentResult (JSON) or AbortController (when streaming)
693
+ */
694
+ async answerAgent(request, callbacks) {
695
+ return this.performAnswerAgent("/agents/answer", request, callbacks);
696
+ }
697
+ /**
698
+ * Query Builder Agent - Translates natural language into structured search queries
699
+ * Uses an LLM to generate optimized Bleve queries from user intent
700
+ * @param request - Query builder request with intent and optional table/schema context
701
+ * @returns Promise with QueryBuilderResult containing the generated query, explanation, and confidence
702
+ */
703
+ async queryBuilderAgent(request) {
704
+ const { data, error } = await this.client.POST("/agents/query-builder", {
301
705
  body: request
302
706
  });
303
- if (error) {
304
- throw new Error(`Query failed: ${error.error}`);
707
+ if (error) throw new Error(`Query builder agent failed: ${error.error}`);
708
+ return data;
709
+ }
710
+ /**
711
+ * Private helper for Chat Agent requests to handle streaming and non-streaming responses
712
+ */
713
+ async performChatAgent(path, request, callbacks) {
714
+ const headers = {
715
+ "Content-Type": "application/json",
716
+ Accept: "text/event-stream, application/json"
717
+ };
718
+ if (this.config.auth) {
719
+ const auth = btoa(`${this.config.auth.username}:${this.config.auth.password}`);
720
+ headers["Authorization"] = `Basic ${auth}`;
305
721
  }
306
- return data?.responses?.[0];
722
+ Object.assign(headers, this.config.headers);
723
+ const abortController = new AbortController();
724
+ const response = await fetch(`${this.config.baseUrl}${path}`, {
725
+ method: "POST",
726
+ headers,
727
+ body: JSON.stringify(request),
728
+ signal: abortController.signal
729
+ });
730
+ if (!response.ok) {
731
+ const errorText = await response.text();
732
+ throw new Error(`Chat agent request failed: ${response.status} ${errorText}`);
733
+ }
734
+ if (!response.body) {
735
+ throw new Error("Response body is null");
736
+ }
737
+ const contentType = response.headers.get("content-type") || "";
738
+ const isJSON = contentType.includes("application/json");
739
+ if (isJSON) {
740
+ const result = await response.json();
741
+ return result;
742
+ }
743
+ if (callbacks) {
744
+ const reader = response.body.getReader();
745
+ const decoder = new TextDecoder();
746
+ let buffer = "";
747
+ let currentEvent = "";
748
+ (async () => {
749
+ try {
750
+ while (true) {
751
+ const { done, value } = await reader.read();
752
+ if (done) break;
753
+ buffer += decoder.decode(value, { stream: true });
754
+ const lines = buffer.split("\n");
755
+ buffer = lines.pop() || "";
756
+ for (const line of lines) {
757
+ if (!line.trim()) {
758
+ currentEvent = "";
759
+ continue;
760
+ }
761
+ if (line.startsWith("event: ")) {
762
+ currentEvent = line.slice(7).trim();
763
+ } else if (line.startsWith("data: ")) {
764
+ const data = line.slice(6).trim();
765
+ try {
766
+ switch (currentEvent) {
767
+ case "classification":
768
+ if (callbacks.onClassification) {
769
+ const classData = JSON.parse(data);
770
+ callbacks.onClassification(classData);
771
+ }
772
+ break;
773
+ case "clarification_required":
774
+ if (callbacks.onClarificationRequired) {
775
+ const clarification = JSON.parse(data);
776
+ callbacks.onClarificationRequired(clarification);
777
+ }
778
+ break;
779
+ case "filter_applied":
780
+ if (callbacks.onFilterApplied) {
781
+ const filter = JSON.parse(data);
782
+ callbacks.onFilterApplied(filter);
783
+ }
784
+ break;
785
+ case "search_executed":
786
+ if (callbacks.onSearchExecuted) {
787
+ const searchData = JSON.parse(data);
788
+ callbacks.onSearchExecuted(searchData);
789
+ }
790
+ break;
791
+ case "websearch_executed":
792
+ if (callbacks.onWebSearchExecuted) {
793
+ const webSearchData = JSON.parse(data);
794
+ callbacks.onWebSearchExecuted(webSearchData);
795
+ }
796
+ break;
797
+ case "fetch_executed":
798
+ if (callbacks.onFetchExecuted) {
799
+ const fetchData = JSON.parse(data);
800
+ callbacks.onFetchExecuted(fetchData);
801
+ }
802
+ break;
803
+ case "hit":
804
+ if (callbacks.onHit) {
805
+ const hit = JSON.parse(data);
806
+ callbacks.onHit(hit);
807
+ }
808
+ break;
809
+ case "answer":
810
+ if (callbacks.onAnswer) {
811
+ callbacks.onAnswer(data);
812
+ }
813
+ break;
814
+ case "done":
815
+ if (callbacks.onDone) {
816
+ const doneData = JSON.parse(data);
817
+ callbacks.onDone(doneData);
818
+ }
819
+ return;
820
+ case "error":
821
+ if (callbacks.onError) {
822
+ const error = JSON.parse(data);
823
+ callbacks.onError(error);
824
+ }
825
+ throw new Error(data);
826
+ }
827
+ } catch (e) {
828
+ console.warn("Failed to parse SSE data:", currentEvent, data, e);
829
+ }
830
+ }
831
+ }
832
+ }
833
+ } catch (error) {
834
+ if (error.name !== "AbortError") {
835
+ console.error("Chat agent streaming error:", error);
836
+ }
837
+ }
838
+ })();
839
+ }
840
+ return abortController;
841
+ }
842
+ /**
843
+ * Chat Agent - Conversational RAG with multi-turn history and tool calling
844
+ * Supports filter refinement, clarification requests, and streaming responses
845
+ * @param request - Chat agent request with conversation history and generator config
846
+ * @param callbacks - Optional callbacks for SSE events (classification, clarification_required, filter_applied, hit, answer, done, error)
847
+ * @returns Promise with ChatAgentResult (JSON) or AbortController (when streaming)
848
+ */
849
+ async chatAgent(request, callbacks) {
850
+ return this.performChatAgent("/agents/chat", request, callbacks);
307
851
  }
308
852
  /**
309
853
  * Get the underlying OpenAPI client for advanced use cases
@@ -313,9 +857,184 @@ var AntflyClient = class {
313
857
  }
314
858
  };
315
859
 
860
+ // src/query-helpers.ts
861
+ function queryString(query, boost) {
862
+ return {
863
+ query,
864
+ boost: boost ?? void 0
865
+ };
866
+ }
867
+ function term(term2, field, boost) {
868
+ return {
869
+ term: term2,
870
+ field,
871
+ boost: boost ?? void 0
872
+ };
873
+ }
874
+ function match(match2, field, options) {
875
+ return {
876
+ match: match2,
877
+ field,
878
+ analyzer: options?.analyzer,
879
+ boost: options?.boost,
880
+ prefix_length: options?.prefix_length,
881
+ fuzziness: options?.fuzziness,
882
+ operator: options?.operator
883
+ };
884
+ }
885
+ function matchPhrase(matchPhrase2, field, options) {
886
+ return {
887
+ match_phrase: matchPhrase2,
888
+ field,
889
+ analyzer: options?.analyzer,
890
+ boost: options?.boost,
891
+ fuzziness: options?.fuzziness
892
+ };
893
+ }
894
+ function prefix(prefix2, field, boost) {
895
+ return {
896
+ prefix: prefix2,
897
+ field,
898
+ boost: boost ?? void 0
899
+ };
900
+ }
901
+ function fuzzy(term2, field, options) {
902
+ return {
903
+ term: term2,
904
+ field,
905
+ fuzziness: options?.fuzziness,
906
+ prefix_length: options?.prefix_length,
907
+ boost: options?.boost
908
+ };
909
+ }
910
+ function numericRange(field, options) {
911
+ return {
912
+ field,
913
+ min: options.min,
914
+ max: options.max,
915
+ inclusive_min: options.inclusive_min,
916
+ inclusive_max: options.inclusive_max,
917
+ boost: options.boost
918
+ };
919
+ }
920
+ function dateRange(field, options) {
921
+ return {
922
+ field,
923
+ start: options.start,
924
+ end: options.end,
925
+ inclusive_start: options.inclusive_start,
926
+ inclusive_end: options.inclusive_end,
927
+ datetime_parser: options.datetime_parser,
928
+ boost: options.boost
929
+ };
930
+ }
931
+ function matchAll(boost) {
932
+ return {
933
+ match_all: {},
934
+ boost: boost ?? void 0
935
+ };
936
+ }
937
+ function matchNone(boost) {
938
+ return {
939
+ match_none: {},
940
+ boost: boost ?? void 0
941
+ };
942
+ }
943
+ function boolean(options) {
944
+ const result = {
945
+ boost: options.boost
946
+ };
947
+ if (options.must && options.must.length > 0) {
948
+ result.must = {
949
+ conjuncts: options.must
950
+ };
951
+ }
952
+ if (options.should && options.should.length > 0) {
953
+ result.should = {
954
+ disjuncts: options.should,
955
+ min: options.minShouldMatch
956
+ };
957
+ }
958
+ if (options.mustNot && options.mustNot.length > 0) {
959
+ result.must_not = {
960
+ disjuncts: options.mustNot
961
+ };
962
+ }
963
+ if (options.filter) {
964
+ result.filter = options.filter;
965
+ }
966
+ return result;
967
+ }
968
+ function conjunction(queries) {
969
+ return {
970
+ conjuncts: queries
971
+ };
972
+ }
973
+ function disjunction(queries, min) {
974
+ return {
975
+ disjuncts: queries,
976
+ min
977
+ };
978
+ }
979
+ function docIds(ids, boost) {
980
+ return {
981
+ ids,
982
+ boost: boost ?? void 0
983
+ };
984
+ }
985
+ function geoDistance(field, location, distance, boost) {
986
+ return {
987
+ field,
988
+ location,
989
+ distance,
990
+ boost: boost ?? void 0
991
+ };
992
+ }
993
+ function geoBoundingBox(field, bounds, boost) {
994
+ return {
995
+ field,
996
+ top_left: bounds.top_left,
997
+ bottom_right: bounds.bottom_right,
998
+ boost: boost ?? void 0
999
+ };
1000
+ }
1001
+
1002
+ // src/types.ts
1003
+ var embedderProviders = [
1004
+ "ollama",
1005
+ "gemini",
1006
+ "openai",
1007
+ "bedrock"
1008
+ ];
1009
+ var generatorProviders = [
1010
+ "ollama",
1011
+ "gemini",
1012
+ "openai",
1013
+ "bedrock",
1014
+ "anthropic"
1015
+ ];
1016
+
316
1017
  // src/index.ts
317
1018
  var index_default = AntflyClient;
318
1019
  // Annotate the CommonJS export names for ESM import in node:
319
1020
  0 && (module.exports = {
320
- AntflyClient
1021
+ AntflyClient,
1022
+ boolean,
1023
+ conjunction,
1024
+ dateRange,
1025
+ disjunction,
1026
+ docIds,
1027
+ embedderProviders,
1028
+ fuzzy,
1029
+ generatorProviders,
1030
+ geoBoundingBox,
1031
+ geoDistance,
1032
+ match,
1033
+ matchAll,
1034
+ matchNone,
1035
+ matchPhrase,
1036
+ numericRange,
1037
+ prefix,
1038
+ queryString,
1039
+ term
321
1040
  });