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