@ai-sdk/react 2.1.0-beta.9 → 3.0.0-beta.101

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/CHANGELOG.md CHANGED
@@ -1,5 +1,685 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 3.0.0-beta.101
4
+
5
+ ### Patch Changes
6
+
7
+ - ai@6.0.0-beta.101
8
+
9
+ ## 3.0.0-beta.100
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [8370068]
14
+ - ai@6.0.0-beta.100
15
+
16
+ ## 3.0.0-beta.99
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies [384142c]
21
+ - ai@6.0.0-beta.99
22
+
23
+ ## 3.0.0-beta.98
24
+
25
+ ### Patch Changes
26
+
27
+ - Updated dependencies [b681d7d]
28
+ - ai@6.0.0-beta.98
29
+ - @ai-sdk/provider-utils@4.0.0-beta.33
30
+
31
+ ## 3.0.0-beta.97
32
+
33
+ ### Patch Changes
34
+
35
+ - Updated dependencies [32d8dbb]
36
+ - @ai-sdk/provider-utils@4.0.0-beta.32
37
+ - ai@6.0.0-beta.97
38
+
39
+ ## 3.0.0-beta.96
40
+
41
+ ### Patch Changes
42
+
43
+ - a322efa: Added finishReason on useChat onFinish callbck
44
+ - Updated dependencies [a322efa]
45
+ - ai@6.0.0-beta.96
46
+
47
+ ## 3.0.0-beta.95
48
+
49
+ ### Patch Changes
50
+
51
+ - Updated dependencies [eb8d1cb]
52
+ - ai@6.0.0-beta.95
53
+
54
+ ## 3.0.0-beta.94
55
+
56
+ ### Patch Changes
57
+
58
+ - ab1087b: feat(ai): `chat.addToolResult()` is now `chat.addToolOutput()`
59
+ - Updated dependencies [ab1087b]
60
+ - ai@6.0.0-beta.94
61
+
62
+ ## 3.0.0-beta.93
63
+
64
+ ### Patch Changes
65
+
66
+ - ai@6.0.0-beta.93
67
+ - @ai-sdk/provider-utils@4.0.0-beta.31
68
+
69
+ ## 3.0.0-beta.92
70
+
71
+ ### Patch Changes
72
+
73
+ - Updated dependencies [97b1d77]
74
+ - ai@6.0.0-beta.92
75
+
76
+ ## 3.0.0-beta.91
77
+
78
+ ### Patch Changes
79
+
80
+ - Updated dependencies [4f16c37]
81
+ - @ai-sdk/provider-utils@4.0.0-beta.30
82
+ - ai@6.0.0-beta.91
83
+
84
+ ## 3.0.0-beta.90
85
+
86
+ ### Patch Changes
87
+
88
+ - ai@6.0.0-beta.90
89
+ - @ai-sdk/provider-utils@4.0.0-beta.29
90
+
91
+ ## 3.0.0-beta.89
92
+
93
+ ### Patch Changes
94
+
95
+ - Updated dependencies [d59ce25]
96
+ - ai@6.0.0-beta.89
97
+
98
+ ## 3.0.0-beta.88
99
+
100
+ ### Patch Changes
101
+
102
+ - Updated dependencies [22ef5c6]
103
+ - ai@6.0.0-beta.88
104
+
105
+ ## 3.0.0-beta.87
106
+
107
+ ### Patch Changes
108
+
109
+ - Updated dependencies [ca13d26]
110
+ - ai@6.0.0-beta.87
111
+
112
+ ## 3.0.0-beta.86
113
+
114
+ ### Patch Changes
115
+
116
+ - Updated dependencies [36b175c]
117
+ - ai@6.0.0-beta.86
118
+
119
+ ## 3.0.0-beta.85
120
+
121
+ ### Patch Changes
122
+
123
+ - ai@6.0.0-beta.85
124
+
125
+ ## 3.0.0-beta.84
126
+
127
+ ### Patch Changes
128
+
129
+ - Updated dependencies [016b111]
130
+ - @ai-sdk/provider-utils@4.0.0-beta.28
131
+ - ai@6.0.0-beta.84
132
+
133
+ ## 3.0.0-beta.83
134
+
135
+ ### Patch Changes
136
+
137
+ - Updated dependencies [e1f6e8e]
138
+ - ai@6.0.0-beta.83
139
+
140
+ ## 3.0.0-beta.82
141
+
142
+ ### Patch Changes
143
+
144
+ - Updated dependencies [37c58a0]
145
+ - ai@6.0.0-beta.82
146
+ - @ai-sdk/provider-utils@4.0.0-beta.27
147
+
148
+ ## 3.0.0-beta.81
149
+
150
+ ### Patch Changes
151
+
152
+ - ai@6.0.0-beta.81
153
+
154
+ ## 3.0.0-beta.80
155
+
156
+ ### Patch Changes
157
+
158
+ - Updated dependencies [9524761]
159
+ - ai@6.0.0-beta.80
160
+
161
+ ## 3.0.0-beta.79
162
+
163
+ ### Patch Changes
164
+
165
+ - Updated dependencies [d1bdadb]
166
+ - ai@6.0.0-beta.79
167
+ - @ai-sdk/provider-utils@4.0.0-beta.26
168
+
169
+ ## 3.0.0-beta.78
170
+
171
+ ### Patch Changes
172
+
173
+ - ai@6.0.0-beta.78
174
+ - @ai-sdk/provider-utils@4.0.0-beta.25
175
+
176
+ ## 3.0.0-beta.77
177
+
178
+ ### Patch Changes
179
+
180
+ - Updated dependencies [0c3b58b]
181
+ - ai@6.0.0-beta.77
182
+ - @ai-sdk/provider-utils@4.0.0-beta.24
183
+
184
+ ## 3.0.0-beta.76
185
+
186
+ ### Patch Changes
187
+
188
+ - Updated dependencies [a755db5]
189
+ - ai@6.0.0-beta.76
190
+ - @ai-sdk/provider-utils@4.0.0-beta.23
191
+
192
+ ## 3.0.0-beta.75
193
+
194
+ ### Patch Changes
195
+
196
+ - Updated dependencies [58920e0]
197
+ - Updated dependencies [58920e0]
198
+ - ai@6.0.0-beta.75
199
+ - @ai-sdk/provider-utils@4.0.0-beta.22
200
+
201
+ ## 3.0.0-beta.74
202
+
203
+ ### Patch Changes
204
+
205
+ - Updated dependencies [293a6b7]
206
+ - @ai-sdk/provider-utils@4.0.0-beta.21
207
+ - ai@6.0.0-beta.74
208
+
209
+ ## 3.0.0-beta.73
210
+
211
+ ### Patch Changes
212
+
213
+ - Updated dependencies [754df61]
214
+ - ai@6.0.0-beta.73
215
+
216
+ ## 3.0.0-beta.72
217
+
218
+ ### Patch Changes
219
+
220
+ - Updated dependencies [eca63f3]
221
+ - ai@6.0.0-beta.72
222
+
223
+ ## 3.0.0-beta.71
224
+
225
+ ### Patch Changes
226
+
227
+ - Updated dependencies [077aea3]
228
+ - ai@6.0.0-beta.71
229
+
230
+ ## 3.0.0-beta.70
231
+
232
+ ### Patch Changes
233
+
234
+ - Updated dependencies [d7bae86]
235
+ - ai@6.0.0-beta.70
236
+
237
+ ## 3.0.0-beta.69
238
+
239
+ ### Patch Changes
240
+
241
+ - Updated dependencies [d5b25ee]
242
+ - ai@6.0.0-beta.69
243
+
244
+ ## 3.0.0-beta.68
245
+
246
+ ### Patch Changes
247
+
248
+ - Updated dependencies [9b83947]
249
+ - ai@6.0.0-beta.68
250
+
251
+ ## 3.0.0-beta.67
252
+
253
+ ### Patch Changes
254
+
255
+ - ai@6.0.0-beta.67
256
+
257
+ ## 3.0.0-beta.66
258
+
259
+ ### Patch Changes
260
+
261
+ - Updated dependencies [fca786b]
262
+ - Updated dependencies [fca786b]
263
+ - ai@6.0.0-beta.66
264
+ - @ai-sdk/provider-utils@4.0.0-beta.20
265
+
266
+ ## 3.0.0-beta.65
267
+
268
+ ### Patch Changes
269
+
270
+ - Updated dependencies [dce4e7b]
271
+ - ai@6.0.0-beta.65
272
+
273
+ ## 3.0.0-beta.64
274
+
275
+ ### Patch Changes
276
+
277
+ - Updated dependencies [2d28066]
278
+ - ai@6.0.0-beta.64
279
+
280
+ ## 3.0.0-beta.63
281
+
282
+ ### Patch Changes
283
+
284
+ - Updated dependencies [a7da2b6]
285
+ - ai@6.0.0-beta.63
286
+
287
+ ## 3.0.0-beta.62
288
+
289
+ ### Patch Changes
290
+
291
+ - Updated dependencies [95b77e2]
292
+ - ai@6.0.0-beta.62
293
+
294
+ ## 3.0.0-beta.61
295
+
296
+ ### Patch Changes
297
+
298
+ - Updated dependencies [c98373a]
299
+ - ai@6.0.0-beta.61
300
+
301
+ ## 3.0.0-beta.60
302
+
303
+ ### Patch Changes
304
+
305
+ - Updated dependencies [2b49dae]
306
+ - ai@6.0.0-beta.60
307
+
308
+ ## 3.0.0-beta.59
309
+
310
+ ### Patch Changes
311
+
312
+ - Updated dependencies [e062079]
313
+ - ai@6.0.0-beta.59
314
+
315
+ ## 3.0.0-beta.58
316
+
317
+ ### Patch Changes
318
+
319
+ - Updated dependencies [a417a34]
320
+ - ai@6.0.0-beta.58
321
+
322
+ ## 3.0.0-beta.57
323
+
324
+ ### Patch Changes
325
+
326
+ - Updated dependencies [61f7b0f]
327
+ - ai@6.0.0-beta.57
328
+
329
+ ## 3.0.0-beta.56
330
+
331
+ ### Patch Changes
332
+
333
+ - Updated dependencies [3794514]
334
+ - @ai-sdk/provider-utils@4.0.0-beta.19
335
+ - ai@6.0.0-beta.56
336
+
337
+ ## 3.0.0-beta.55
338
+
339
+ ### Patch Changes
340
+
341
+ - Updated dependencies [42cf7ed]
342
+ - ai@6.0.0-beta.55
343
+
344
+ ## 3.0.0-beta.54
345
+
346
+ ### Patch Changes
347
+
348
+ - Updated dependencies [9388ff1]
349
+ - ai@6.0.0-beta.54
350
+
351
+ ## 3.0.0-beta.53
352
+
353
+ ### Patch Changes
354
+
355
+ - ai@6.0.0-beta.53
356
+
357
+ ## 3.0.0-beta.52
358
+
359
+ ### Patch Changes
360
+
361
+ - ai@6.0.0-beta.52
362
+
363
+ ## 3.0.0-beta.51
364
+
365
+ ### Patch Changes
366
+
367
+ - Updated dependencies [5e313e3]
368
+ - ai@6.0.0-beta.51
369
+
370
+ ## 3.0.0-beta.50
371
+
372
+ ### Patch Changes
373
+
374
+ - Updated dependencies [4812235]
375
+ - Updated dependencies [81d4308]
376
+ - ai@6.0.0-beta.50
377
+ - @ai-sdk/provider-utils@4.0.0-beta.18
378
+
379
+ ## 3.0.0-beta.49
380
+
381
+ ### Patch Changes
382
+
383
+ - Updated dependencies [703459a]
384
+ - @ai-sdk/provider-utils@4.0.0-beta.17
385
+ - ai@6.0.0-beta.49
386
+
387
+ ## 3.0.0-beta.48
388
+
389
+ ### Patch Changes
390
+
391
+ - Updated dependencies [7f2c9b6]
392
+ - ai@6.0.0-beta.48
393
+
394
+ ## 3.0.0-beta.47
395
+
396
+ ### Patch Changes
397
+
398
+ - Updated dependencies [c62ecf0]
399
+ - ai@6.0.0-beta.47
400
+
401
+ ## 3.0.0-beta.46
402
+
403
+ ### Patch Changes
404
+
405
+ - ai@6.0.0-beta.46
406
+
407
+ ## 3.0.0-beta.45
408
+
409
+ ### Patch Changes
410
+
411
+ - Updated dependencies [48454ab]
412
+ - ai@6.0.0-beta.45
413
+
414
+ ## 3.0.0-beta.44
415
+
416
+ ### Patch Changes
417
+
418
+ - Updated dependencies [2b1bf9d]
419
+ - ai@6.0.0-beta.44
420
+
421
+ ## 3.0.0-beta.43
422
+
423
+ ### Patch Changes
424
+
425
+ - Updated dependencies [27e8c3a]
426
+ - ai@6.0.0-beta.43
427
+
428
+ ## 3.0.0-beta.42
429
+
430
+ ### Patch Changes
431
+
432
+ - Updated dependencies [6306603]
433
+ - @ai-sdk/provider-utils@4.0.0-beta.16
434
+ - ai@6.0.0-beta.42
435
+
436
+ ## 3.0.0-beta.41
437
+
438
+ ### Patch Changes
439
+
440
+ - Updated dependencies [f0b2157]
441
+ - @ai-sdk/provider-utils@4.0.0-beta.15
442
+ - ai@6.0.0-beta.41
443
+
444
+ ## 3.0.0-beta.40
445
+
446
+ ### Patch Changes
447
+
448
+ - Updated dependencies [3b1d015]
449
+ - @ai-sdk/provider-utils@4.0.0-beta.14
450
+ - ai@6.0.0-beta.40
451
+
452
+ ## 3.0.0-beta.39
453
+
454
+ ### Patch Changes
455
+
456
+ - f6f0c5a: chore: remove zod from ui packages
457
+ - Updated dependencies [f6f0c5a]
458
+ - ai@6.0.0-beta.39
459
+
460
+ ## 3.0.0-beta.38
461
+
462
+ ### Patch Changes
463
+
464
+ - Updated dependencies [d116b4b]
465
+ - @ai-sdk/provider-utils@4.0.0-beta.13
466
+ - ai@6.0.0-beta.38
467
+
468
+ ## 3.0.0-beta.37
469
+
470
+ ### Patch Changes
471
+
472
+ - Updated dependencies [7e32fea]
473
+ - @ai-sdk/provider-utils@4.0.0-beta.12
474
+ - ai@6.0.0-beta.37
475
+
476
+ ## 3.0.0-beta.36
477
+
478
+ ### Patch Changes
479
+
480
+ - ai@6.0.0-beta.36
481
+
482
+ ## 3.0.0-beta.35
483
+
484
+ ### Patch Changes
485
+
486
+ - ai@6.0.0-beta.35
487
+
488
+ ## 3.0.0-beta.34
489
+
490
+ ### Patch Changes
491
+
492
+ - Updated dependencies [bb10a89]
493
+ - ai@6.0.0-beta.34
494
+
495
+ ## 3.0.0-beta.33
496
+
497
+ ### Patch Changes
498
+
499
+ - Updated dependencies [f733285]
500
+ - ai@6.0.0-beta.33
501
+
502
+ ## 3.0.0-beta.32
503
+
504
+ ### Patch Changes
505
+
506
+ - Updated dependencies [7e4649f]
507
+ - ai@6.0.0-beta.32
508
+
509
+ ## 3.0.0-beta.31
510
+
511
+ ### Patch Changes
512
+
513
+ - 95f65c2: chore: use import \* from zod/v4
514
+ - Updated dependencies [95f65c2]
515
+ - Updated dependencies [95f65c2]
516
+ - @ai-sdk/provider-utils@4.0.0-beta.11
517
+ - ai@6.0.0-beta.31
518
+
519
+ ## 3.0.0-beta.30
520
+
521
+ ### Patch Changes
522
+
523
+ - ai@6.0.0-beta.30
524
+
525
+ ## 3.0.0-beta.29
526
+
527
+ ### Major Changes
528
+
529
+ - dee8b05: ai SDK 6 beta
530
+
531
+ ### Patch Changes
532
+
533
+ - Updated dependencies [dee8b05]
534
+ - ai@6.0.0-beta.29
535
+ - @ai-sdk/provider-utils@4.0.0-beta.10
536
+
537
+ ## 2.1.0-beta.28
538
+
539
+ ### Patch Changes
540
+
541
+ - Updated dependencies [521c537]
542
+ - @ai-sdk/provider-utils@3.1.0-beta.9
543
+ - ai@5.1.0-beta.28
544
+
545
+ ## 2.1.0-beta.27
546
+
547
+ ### Patch Changes
548
+
549
+ - Updated dependencies [e06565c]
550
+ - @ai-sdk/provider-utils@3.1.0-beta.8
551
+ - ai@5.1.0-beta.27
552
+
553
+ ## 2.1.0-beta.26
554
+
555
+ ### Patch Changes
556
+
557
+ - Updated dependencies [c99da05]
558
+ - ai@5.1.0-beta.26
559
+
560
+ ## 2.1.0-beta.25
561
+
562
+ ### Patch Changes
563
+
564
+ - Updated dependencies [457f1c6]
565
+ - ai@5.1.0-beta.25
566
+
567
+ ## 2.1.0-beta.24
568
+
569
+ ### Patch Changes
570
+
571
+ - Updated dependencies [90e5bdd]
572
+ - ai@5.1.0-beta.24
573
+
574
+ ## 2.1.0-beta.23
575
+
576
+ ### Patch Changes
577
+
578
+ - ai@5.1.0-beta.23
579
+
580
+ ## 2.1.0-beta.22
581
+
582
+ ### Patch Changes
583
+
584
+ - e8109d3: feat: tool execution approval
585
+ - Updated dependencies [046aa3b]
586
+ - Updated dependencies [e8109d3]
587
+ - Updated dependencies [a5e152d]
588
+ - Updated dependencies [21e20c0]
589
+ - ai@5.1.0-beta.22
590
+ - @ai-sdk/provider-utils@3.1.0-beta.7
591
+
592
+ ## 2.1.0-beta.21
593
+
594
+ ### Patch Changes
595
+
596
+ - ai@5.1.0-beta.21
597
+
598
+ ## 2.1.0-beta.20
599
+
600
+ ### Patch Changes
601
+
602
+ - Updated dependencies [846e80e]
603
+ - ai@5.1.0-beta.20
604
+
605
+ ## 2.1.0-beta.19
606
+
607
+ ### Patch Changes
608
+
609
+ - Updated dependencies [aa0515c]
610
+ - Updated dependencies [e7d9b00]
611
+ - Updated dependencies [b1aeea7]
612
+ - ai@5.1.0-beta.19
613
+
614
+ ## 2.1.0-beta.18
615
+
616
+ ### Patch Changes
617
+
618
+ - Updated dependencies [0adc679]
619
+ - Updated dependencies [9b8d17e]
620
+ - @ai-sdk/provider-utils@3.1.0-beta.6
621
+ - ai@5.1.0-beta.18
622
+
623
+ ## 2.1.0-beta.17
624
+
625
+ ### Patch Changes
626
+
627
+ - ai@5.1.0-beta.17
628
+
629
+ ## 2.1.0-beta.16
630
+
631
+ ### Patch Changes
632
+
633
+ - Updated dependencies [14ca35d]
634
+ - ai@5.1.0-beta.16
635
+
636
+ ## 2.1.0-beta.15
637
+
638
+ ### Patch Changes
639
+
640
+ - ai@5.1.0-beta.15
641
+
642
+ ## 2.1.0-beta.14
643
+
644
+ ### Patch Changes
645
+
646
+ - 10c1322: fix: moved dependency `@ai-sdk/test-server` to devDependencies
647
+ - Updated dependencies [7c3c216]
648
+ - Updated dependencies [8dac895]
649
+ - Updated dependencies [e0d1ea9]
650
+ - Updated dependencies [10c1322]
651
+ - ai@5.1.0-beta.14
652
+ - @ai-sdk/provider-utils@3.1.0-beta.5
653
+
654
+ ## 2.1.0-beta.13
655
+
656
+ ### Patch Changes
657
+
658
+ - Updated dependencies [1c2a4c1]
659
+ - ai@5.1.0-beta.13
660
+
661
+ ## 2.1.0-beta.12
662
+
663
+ ### Patch Changes
664
+
665
+ - ai@5.1.0-beta.12
666
+
667
+ ## 2.1.0-beta.11
668
+
669
+ ### Patch Changes
670
+
671
+ - 4616b86: chore: update zod peer depenedency version
672
+ - Updated dependencies [4616b86]
673
+ - @ai-sdk/provider-utils@3.1.0-beta.4
674
+ - ai@5.1.0-beta.11
675
+
676
+ ## 2.1.0-beta.10
677
+
678
+ ### Patch Changes
679
+
680
+ - Updated dependencies [8c98371]
681
+ - ai@5.1.0-beta.10
682
+
3
683
  ## 2.1.0-beta.9
4
684
 
5
685
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -1,8 +1,6 @@
1
- import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
- import { FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
- import * as z3 from 'zod/v3';
5
- import * as z4 from 'zod/v4';
3
+ import { FlexibleSchema, FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
6
4
 
7
5
  declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {
8
6
  #private;
@@ -24,7 +22,7 @@ type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
24
22
  */
25
23
  setMessages: (messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[])) => void;
26
24
  error: Error | undefined;
27
- } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'status' | 'messages' | 'clearError'>;
25
+ } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError'>;
28
26
  type UseChatOptions<UI_MESSAGE extends UIMessage> = ({
29
27
  chat: Chat<UI_MESSAGE>;
30
28
  } | ChatInit<UI_MESSAGE>) & {
@@ -92,13 +90,13 @@ declare function useCompletion({ api, id, initialCompletion, initialInput, crede
92
90
  experimental_throttle?: number;
93
91
  }): UseCompletionHelpers;
94
92
 
95
- type Experimental_UseObjectOptions<SCHEMA extends z4.core.$ZodType | z3.Schema | Schema, RESULT> = {
93
+ type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {
96
94
  /**
97
95
  * The API endpoint. It should stream JSON that matches the schema as chunked text.
98
96
  */
99
97
  api: string;
100
98
  /**
101
- * A Zod schema that defines the shape of the complete object.
99
+ * A schema that defines the shape of the complete object.
102
100
  */
103
101
  schema: SCHEMA;
104
102
  /**
@@ -171,7 +169,7 @@ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
171
169
  */
172
170
  clear: () => void;
173
171
  };
174
- declare function useObject<SCHEMA extends z4.core.$ZodType | z3.Schema | Schema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
172
+ declare function useObject<SCHEMA extends FlexibleSchema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
175
173
  initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
176
174
  declare const experimental_useObject: typeof useObject;
177
175
 
package/dist/index.d.ts CHANGED
@@ -1,8 +1,6 @@
1
- import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
1
+ import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, DeepPartial } from 'ai';
2
2
  export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
- import { FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
- import * as z3 from 'zod/v3';
5
- import * as z4 from 'zod/v4';
3
+ import { FlexibleSchema, FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
6
4
 
7
5
  declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {
8
6
  #private;
@@ -24,7 +22,7 @@ type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
24
22
  */
25
23
  setMessages: (messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[])) => void;
26
24
  error: Error | undefined;
27
- } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'status' | 'messages' | 'clearError'>;
25
+ } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError'>;
28
26
  type UseChatOptions<UI_MESSAGE extends UIMessage> = ({
29
27
  chat: Chat<UI_MESSAGE>;
30
28
  } | ChatInit<UI_MESSAGE>) & {
@@ -92,13 +90,13 @@ declare function useCompletion({ api, id, initialCompletion, initialInput, crede
92
90
  experimental_throttle?: number;
93
91
  }): UseCompletionHelpers;
94
92
 
95
- type Experimental_UseObjectOptions<SCHEMA extends z4.core.$ZodType | z3.Schema | Schema, RESULT> = {
93
+ type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {
96
94
  /**
97
95
  * The API endpoint. It should stream JSON that matches the schema as chunked text.
98
96
  */
99
97
  api: string;
100
98
  /**
101
- * A Zod schema that defines the shape of the complete object.
99
+ * A schema that defines the shape of the complete object.
102
100
  */
103
101
  schema: SCHEMA;
104
102
  /**
@@ -171,7 +169,7 @@ type Experimental_UseObjectHelpers<RESULT, INPUT> = {
171
169
  */
172
170
  clear: () => void;
173
171
  };
174
- declare function useObject<SCHEMA extends z4.core.$ZodType | z3.Schema | Schema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
172
+ declare function useObject<SCHEMA extends FlexibleSchema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
175
173
  initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
176
174
  declare const experimental_useObject: typeof useObject;
177
175
 
package/dist/index.js CHANGED
@@ -230,7 +230,12 @@ function useChat({
230
230
  error,
231
231
  resumeStream: chatRef.current.resumeStream,
232
232
  status,
233
- addToolResult: chatRef.current.addToolResult
233
+ /**
234
+ * @deprecated Use `addToolOutput` instead.
235
+ */
236
+ addToolResult: chatRef.current.addToolOutput,
237
+ addToolOutput: chatRef.current.addToolOutput,
238
+ addToolApprovalResponse: chatRef.current.addToolApprovalResponse
234
239
  };
235
240
  }
236
241
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n addToolResult: chatRef.current.addToolResult,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends z4.core.$ZodType | z3.Schema | Schema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends z4.core.$ZodType | z3.Schema | Schema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,mBAAqE;;;ACNrE,gBAAyE;;;ACAzE,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAA,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAAqB,oBAAI,IAAgB;AACzC,yCAAmB,oBAAI,IAAgB;AACvC,wCAAkB,oBAAI,IAAgB;AAiCtC,uBAAc,CAAC,YAAwB;AACrC,yBAAK,WAAY,mBAAK,WAAU,OAAO,OAAO;AAC9C,yBAAK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_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASE,QAAO;AACd,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["throttleFunction","import_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -192,7 +192,12 @@ function useChat({
192
192
  error,
193
193
  resumeStream: chatRef.current.resumeStream,
194
194
  status,
195
- addToolResult: chatRef.current.addToolResult
195
+ /**
196
+ * @deprecated Use `addToolOutput` instead.
197
+ */
198
+ addToolResult: chatRef.current.addToolOutput,
199
+ addToolOutput: chatRef.current.addToolOutput,
200
+ addToolApprovalResponse: chatRef.current.addToolApprovalResponse
196
201
  };
197
202
  }
198
203
 
@@ -329,11 +334,7 @@ import {
329
334
  isAbortError,
330
335
  safeValidateTypes
331
336
  } from "@ai-sdk/provider-utils";
332
- import {
333
- asSchema,
334
- isDeepEqualData,
335
- parsePartialJson
336
- } from "ai";
337
+ import { asSchema, isDeepEqualData, parsePartialJson } from "ai";
337
338
  import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
338
339
  import useSWR2 from "swr";
339
340
  var getOriginalFetch = () => fetch;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n addToolResult: chatRef.current.addToolResult,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends z4.core.$ZodType | z3.Schema | Schema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A Zod schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends z4.core.$ZodType | z3.Schema | Schema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAAS,oBAAgE;;;ACAzE,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAA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AAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAAS,oBAAgE;;;ACAzE,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAAqB,oBAAI,IAAgB;AACzC,yCAAmB,oBAAI,IAAgB;AACvC,wCAAkB,oBAAI,IAAgB;AAiCtC,uBAAc,CAAC,YAAwB;AACrC,yBAAK,WAAY,mBAAK,WAAU,OAAO,OAAO;AAC9C,yBAAK,wBAAL;AAAA,IACF;AAEA,sBAAa,MAAM;AACjB,yBAAK,WAAY,mBAAK,WAAU,MAAM,GAAG,EAAE;AAC3C,yBAAK,wBAAL;AAAA,IACF;AAEA,0BAAiB,CAAC,OAAe,YAAwB;AACvD,yBAAK,WAAY;AAAA,QACf,GAAG,mBAAK,WAAU,MAAM,GAAG,KAAK;AAAA;AAAA,QAEhC,KAAK,SAAS,OAAO;AAAA,QACrB,GAAG,mBAAK,WAAU,MAAM,QAAQ,CAAC;AAAA,MACnC;AACA,yBAAK,wBAAL;AAAA,IACF;AAEA,oBAAW,CAAI,UAAgB,gBAAgB,KAAK;AAEpD,wCAA8B,CAC5B,UACA,mBACiB;AACjB,YAAM,WAAW,iBACb,SAAS,UAAU,cAAc,IACjC;AACJ,yBAAK,oBAAmB,IAAI,QAAQ;AACpC,aAAO,MAAM;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;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,MAAM,kBAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,QAAQ,SAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASC,QAAO;AACd,UAAI,aAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "2.1.0-beta.9",
3
+ "version": "3.0.0-beta.101",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -16,14 +16,14 @@
16
16
  },
17
17
  "files": [
18
18
  "dist/**/*",
19
- "CHANGELOG.md"
19
+ "CHANGELOG.md",
20
+ "README.md"
20
21
  ],
21
22
  "dependencies": {
22
23
  "swr": "^2.2.5",
23
24
  "throttleit": "2.1.0",
24
- "@ai-sdk/test-server": "1.0.0-beta.0",
25
- "ai": "5.1.0-beta.9",
26
- "@ai-sdk/provider-utils": "3.1.0-beta.3"
25
+ "@ai-sdk/provider-utils": "4.0.0-beta.33",
26
+ "ai": "6.0.0-beta.101"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@testing-library/jest-dom": "^6.6.3",
@@ -39,17 +39,12 @@
39
39
  "tsup": "^7.2.0",
40
40
  "typescript": "5.8.3",
41
41
  "zod": "3.25.76",
42
+ "@ai-sdk/test-server": "1.0.0-beta.1",
42
43
  "@vercel/ai-tsconfig": "0.0.0",
43
44
  "eslint-config-vercel-ai": "0.0.0"
44
45
  },
45
46
  "peerDependencies": {
46
- "react": "^18 || ^19 || ^19.0.0-rc",
47
- "zod": "^3.25.76 || ^4"
48
- },
49
- "peerDependenciesMeta": {
50
- "zod": {
51
- "optional": true
52
- }
47
+ "react": "^18 || ^19 || ^19.0.0-rc"
53
48
  },
54
49
  "engines": {
55
50
  "node": ">=18"
@@ -72,7 +67,7 @@
72
67
  "scripts": {
73
68
  "build": "pnpm clean && tsup --tsconfig tsconfig.build.json",
74
69
  "build:watch": "pnpm clean && tsup --watch --tsconfig tsconfig.build.json",
75
- "clean": "rm -rf dist *.tsbuildinfo",
70
+ "clean": "del-cli dist *.tsbuildinfo",
76
71
  "lint": "eslint \"./**/*.ts*\"",
77
72
  "type-check": "tsc --build",
78
73
  "prettier-check": "prettier --check \"./**/*.ts*\"",