@ai-sdk/react 2.0.0-canary.8 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -26,10 +26,29 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var __accessCheck = (obj, member, msg) => {
30
+ if (!member.has(obj))
31
+ throw TypeError("Cannot " + msg);
32
+ };
33
+ var __privateGet = (obj, member, getter) => {
34
+ __accessCheck(obj, member, "read from private field");
35
+ return getter ? getter.call(obj) : member.get(obj);
36
+ };
37
+ var __privateAdd = (obj, member, value) => {
38
+ if (member.has(obj))
39
+ throw TypeError("Cannot add the same private member more than once");
40
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
+ };
42
+ var __privateSet = (obj, member, value, setter) => {
43
+ __accessCheck(obj, member, "write to private field");
44
+ setter ? setter.call(obj, value) : member.set(obj, value);
45
+ return value;
46
+ };
29
47
 
30
48
  // src/index.ts
31
49
  var src_exports = {};
32
50
  __export(src_exports, {
51
+ Chat: () => Chat,
33
52
  experimental_useObject: () => experimental_useObject,
34
53
  useChat: () => useChat,
35
54
  useCompletion: () => useCompletion
@@ -37,9 +56,10 @@ __export(src_exports, {
37
56
  module.exports = __toCommonJS(src_exports);
38
57
 
39
58
  // src/use-chat.ts
40
- var import_ai2 = require("ai");
41
- var import_react2 = require("react");
42
- var import_swr = __toESM(require("swr"));
59
+ var import_react = require("react");
60
+
61
+ // src/chat.react.ts
62
+ var import_ai = require("ai");
43
63
 
44
64
  // src/throttle.ts
45
65
  var import_throttleit = __toESM(require("throttleit"));
@@ -47,370 +67,177 @@ function throttle(fn, waitMs) {
47
67
  return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
48
68
  }
49
69
 
50
- // src/util/use-stable-value.ts
51
- var import_ai = require("ai");
52
- var import_react = require("react");
53
- function useStableValue(latestValue) {
54
- const [value, setValue] = (0, import_react.useState)(latestValue);
55
- (0, import_react.useEffect)(() => {
56
- if (!(0, import_ai.isDeepEqualData)(latestValue, value)) {
57
- setValue(latestValue);
58
- }
59
- }, [latestValue, value]);
60
- return value;
61
- }
70
+ // src/chat.react.ts
71
+ var _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;
72
+ var ReactChatState = class {
73
+ constructor(initialMessages = []) {
74
+ __privateAdd(this, _messages, void 0);
75
+ __privateAdd(this, _status, "ready");
76
+ __privateAdd(this, _error, void 0);
77
+ __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
78
+ __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
79
+ __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
80
+ this.pushMessage = (message) => {
81
+ __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
82
+ __privateGet(this, _callMessagesCallbacks).call(this);
83
+ };
84
+ this.popMessage = () => {
85
+ __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
86
+ __privateGet(this, _callMessagesCallbacks).call(this);
87
+ };
88
+ this.replaceMessage = (index, message) => {
89
+ __privateSet(this, _messages, [
90
+ ...__privateGet(this, _messages).slice(0, index),
91
+ // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
92
+ this.snapshot(message),
93
+ ...__privateGet(this, _messages).slice(index + 1)
94
+ ]);
95
+ __privateGet(this, _callMessagesCallbacks).call(this);
96
+ };
97
+ this.snapshot = (value) => structuredClone(value);
98
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
99
+ const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
100
+ __privateGet(this, _messagesCallbacks).add(callback);
101
+ return () => {
102
+ __privateGet(this, _messagesCallbacks).delete(callback);
103
+ };
104
+ };
105
+ this["~registerStatusCallback"] = (onChange) => {
106
+ __privateGet(this, _statusCallbacks).add(onChange);
107
+ return () => {
108
+ __privateGet(this, _statusCallbacks).delete(onChange);
109
+ };
110
+ };
111
+ this["~registerErrorCallback"] = (onChange) => {
112
+ __privateGet(this, _errorCallbacks).add(onChange);
113
+ return () => {
114
+ __privateGet(this, _errorCallbacks).delete(onChange);
115
+ };
116
+ };
117
+ __privateAdd(this, _callMessagesCallbacks, () => {
118
+ __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
119
+ });
120
+ __privateAdd(this, _callStatusCallbacks, () => {
121
+ __privateGet(this, _statusCallbacks).forEach((callback) => callback());
122
+ });
123
+ __privateAdd(this, _callErrorCallbacks, () => {
124
+ __privateGet(this, _errorCallbacks).forEach((callback) => callback());
125
+ });
126
+ __privateSet(this, _messages, initialMessages);
127
+ }
128
+ get status() {
129
+ return __privateGet(this, _status);
130
+ }
131
+ set status(newStatus) {
132
+ __privateSet(this, _status, newStatus);
133
+ __privateGet(this, _callStatusCallbacks).call(this);
134
+ }
135
+ get error() {
136
+ return __privateGet(this, _error);
137
+ }
138
+ set error(newError) {
139
+ __privateSet(this, _error, newError);
140
+ __privateGet(this, _callErrorCallbacks).call(this);
141
+ }
142
+ get messages() {
143
+ return __privateGet(this, _messages);
144
+ }
145
+ set messages(newMessages) {
146
+ __privateSet(this, _messages, [...newMessages]);
147
+ __privateGet(this, _callMessagesCallbacks).call(this);
148
+ }
149
+ };
150
+ _messages = new WeakMap();
151
+ _status = new WeakMap();
152
+ _error = new WeakMap();
153
+ _messagesCallbacks = new WeakMap();
154
+ _statusCallbacks = new WeakMap();
155
+ _errorCallbacks = new WeakMap();
156
+ _callMessagesCallbacks = new WeakMap();
157
+ _callStatusCallbacks = new WeakMap();
158
+ _callErrorCallbacks = new WeakMap();
159
+ var _state;
160
+ var Chat = class extends import_ai.AbstractChat {
161
+ constructor({ messages, ...init }) {
162
+ const state = new ReactChatState(messages);
163
+ super({ ...init, state });
164
+ __privateAdd(this, _state, void 0);
165
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
166
+ this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
167
+ this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
168
+ __privateSet(this, _state, state);
169
+ }
170
+ };
171
+ _state = new WeakMap();
62
172
 
63
173
  // src/use-chat.ts
64
174
  function useChat({
65
- api = "/api/chat",
66
- id,
67
- initialMessages,
68
- initialInput = "",
69
- sendExtraMessageFields,
70
- onToolCall,
71
- experimental_prepareRequestBody,
72
- maxSteps = 1,
73
- streamProtocol = "data",
74
- onResponse,
75
- onFinish,
76
- onError,
77
- credentials,
78
- headers,
79
- body,
80
- generateId = import_ai2.generateId,
81
- fetch: fetch2,
82
- keepLastMessageOnError = true,
83
- experimental_throttle: throttleWaitMs
175
+ experimental_throttle: throttleWaitMs,
176
+ resume = false,
177
+ ...options
84
178
  } = {}) {
85
- const [hookId] = (0, import_react2.useState)(generateId);
86
- const chatId = id != null ? id : hookId;
87
- const chatKey = typeof api === "string" ? [api, chatId] : chatId;
88
- const stableInitialMessages = useStableValue(initialMessages != null ? initialMessages : []);
89
- const processedInitialMessages = (0, import_react2.useMemo)(
90
- () => (0, import_ai2.fillMessageParts)(stableInitialMessages),
91
- [stableInitialMessages]
92
- );
93
- const { data: messages, mutate } = (0, import_swr.default)(
94
- [chatKey, "messages"],
95
- null,
96
- { fallbackData: processedInitialMessages }
97
- );
98
- const messagesRef = (0, import_react2.useRef)(messages || []);
99
- (0, import_react2.useEffect)(() => {
100
- messagesRef.current = messages || [];
101
- }, [messages]);
102
- const { data: streamData, mutate: mutateStreamData } = (0, import_swr.default)([chatKey, "streamData"], null);
103
- const streamDataRef = (0, import_react2.useRef)(streamData);
104
- (0, import_react2.useEffect)(() => {
105
- streamDataRef.current = streamData;
106
- }, [streamData]);
107
- const { data: status = "ready", mutate: mutateStatus } = (0, import_swr.default)([chatKey, "status"], null);
108
- const { data: error = void 0, mutate: setError } = (0, import_swr.default)([chatKey, "error"], null);
109
- const abortControllerRef = (0, import_react2.useRef)(null);
110
- const extraMetadataRef = (0, import_react2.useRef)({
111
- credentials,
112
- headers,
113
- body
114
- });
115
- (0, import_react2.useEffect)(() => {
116
- extraMetadataRef.current = {
117
- credentials,
118
- headers,
119
- body
120
- };
121
- }, [credentials, headers, body]);
122
- const triggerRequest = (0, import_react2.useCallback)(
123
- async (chatRequest) => {
124
- var _a, _b;
125
- mutateStatus("submitted");
126
- setError(void 0);
127
- const chatMessages = (0, import_ai2.fillMessageParts)(chatRequest.messages);
128
- const messageCount = chatMessages.length;
129
- const maxStep = (0, import_ai2.extractMaxToolInvocationStep)(
130
- (_a = chatMessages[chatMessages.length - 1]) == null ? void 0 : _a.toolInvocations
131
- );
132
- try {
133
- const abortController = new AbortController();
134
- abortControllerRef.current = abortController;
135
- const throttledMutate = throttle(mutate, throttleWaitMs);
136
- const throttledMutateStreamData = throttle(
137
- mutateStreamData,
138
- throttleWaitMs
139
- );
140
- const previousMessages = messagesRef.current;
141
- throttledMutate(chatMessages, false);
142
- const constructedMessagesPayload = sendExtraMessageFields ? chatMessages : chatMessages.map(
143
- ({
144
- role,
145
- content,
146
- experimental_attachments,
147
- data,
148
- annotations,
149
- toolInvocations,
150
- parts
151
- }) => ({
152
- role,
153
- content,
154
- ...experimental_attachments !== void 0 && {
155
- experimental_attachments
156
- },
157
- ...data !== void 0 && { data },
158
- ...annotations !== void 0 && { annotations },
159
- ...toolInvocations !== void 0 && { toolInvocations },
160
- ...parts !== void 0 && { parts }
161
- })
162
- );
163
- const existingData = streamDataRef.current;
164
- await (0, import_ai2.callChatApi)({
165
- api,
166
- body: (_b = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
167
- id: chatId,
168
- messages: chatMessages,
169
- requestData: chatRequest.data,
170
- requestBody: chatRequest.body
171
- })) != null ? _b : {
172
- id: chatId,
173
- messages: constructedMessagesPayload,
174
- data: chatRequest.data,
175
- ...extraMetadataRef.current.body,
176
- ...chatRequest.body
177
- },
178
- streamProtocol,
179
- credentials: extraMetadataRef.current.credentials,
180
- headers: {
181
- ...extraMetadataRef.current.headers,
182
- ...chatRequest.headers
183
- },
184
- abortController: () => abortControllerRef.current,
185
- restoreMessagesOnFailure() {
186
- if (!keepLastMessageOnError) {
187
- throttledMutate(previousMessages, false);
188
- }
189
- },
190
- onResponse,
191
- onUpdate({ message, data, replaceLastMessage }) {
192
- mutateStatus("streaming");
193
- throttledMutate(
194
- [
195
- ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
196
- message
197
- ],
198
- false
199
- );
200
- if (data == null ? void 0 : data.length) {
201
- throttledMutateStreamData(
202
- [...existingData != null ? existingData : [], ...data],
203
- false
204
- );
205
- }
206
- },
207
- onToolCall,
208
- onFinish,
209
- generateId,
210
- fetch: fetch2,
211
- lastMessage: chatMessages[chatMessages.length - 1]
212
- });
213
- abortControllerRef.current = null;
214
- mutateStatus("ready");
215
- } catch (err) {
216
- if (err.name === "AbortError") {
217
- abortControllerRef.current = null;
218
- mutateStatus("ready");
219
- return null;
220
- }
221
- if (onError && err instanceof Error) {
222
- onError(err);
223
- }
224
- setError(err);
225
- mutateStatus("error");
226
- }
227
- const messages2 = messagesRef.current;
228
- if ((0, import_ai2.shouldResubmitMessages)({
229
- originalMaxToolInvocationStep: maxStep,
230
- originalMessageCount: messageCount,
231
- maxSteps,
232
- messages: messages2
233
- })) {
234
- await triggerRequest({ messages: messages2 });
235
- }
236
- },
237
- [
238
- mutate,
239
- mutateStatus,
240
- api,
241
- extraMetadataRef,
242
- onResponse,
243
- onFinish,
244
- onError,
245
- setError,
246
- mutateStreamData,
247
- streamDataRef,
248
- streamProtocol,
249
- sendExtraMessageFields,
250
- experimental_prepareRequestBody,
251
- onToolCall,
252
- maxSteps,
253
- messagesRef,
254
- abortControllerRef,
255
- generateId,
256
- fetch2,
257
- keepLastMessageOnError,
258
- throttleWaitMs,
259
- chatId
260
- ]
179
+ const chatRef = (0, import_react.useRef)(
180
+ "chat" in options ? options.chat : new Chat(options)
261
181
  );
262
- const append = (0, import_react2.useCallback)(
263
- async (message, {
264
- data,
265
- headers: headers2,
266
- body: body2,
267
- experimental_attachments
268
- } = {}) => {
269
- var _a, _b;
270
- const attachmentsForRequest = await (0, import_ai2.prepareAttachmentsForRequest)(
271
- experimental_attachments
272
- );
273
- const messages2 = messagesRef.current.concat({
274
- ...message,
275
- id: (_a = message.id) != null ? _a : generateId(),
276
- createdAt: (_b = message.createdAt) != null ? _b : /* @__PURE__ */ new Date(),
277
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
278
- parts: (0, import_ai2.getMessageParts)(message)
279
- });
280
- return triggerRequest({ messages: messages2, headers: headers2, body: body2, data });
281
- },
282
- [triggerRequest, generateId]
182
+ const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && chatRef.current.id !== options.id;
183
+ if (shouldRecreateChat) {
184
+ chatRef.current = "chat" in options ? options.chat : new Chat(options);
185
+ }
186
+ const optionsId = "id" in options ? options.id : null;
187
+ const subscribeToMessages = (0, import_react.useCallback)(
188
+ (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
189
+ // optionsId is required to trigger re-subscription when the chat ID changes
190
+ // eslint-disable-next-line react-hooks/exhaustive-deps
191
+ [throttleWaitMs, optionsId]
283
192
  );
284
- const reload = (0, import_react2.useCallback)(
285
- async ({ data, headers: headers2, body: body2 } = {}) => {
286
- const messages2 = messagesRef.current;
287
- if (messages2.length === 0) {
288
- return null;
289
- }
290
- const lastMessage = messages2[messages2.length - 1];
291
- return triggerRequest({
292
- messages: lastMessage.role === "assistant" ? messages2.slice(0, -1) : messages2,
293
- headers: headers2,
294
- body: body2,
295
- data
296
- });
297
- },
298
- [triggerRequest]
193
+ const messages = (0, import_react.useSyncExternalStore)(
194
+ subscribeToMessages,
195
+ () => chatRef.current.messages,
196
+ () => chatRef.current.messages
299
197
  );
300
- const stop = (0, import_react2.useCallback)(() => {
301
- if (abortControllerRef.current) {
302
- abortControllerRef.current.abort();
303
- abortControllerRef.current = null;
304
- }
305
- }, []);
306
- const setMessages = (0, import_react2.useCallback)(
307
- (messages2) => {
308
- if (typeof messages2 === "function") {
309
- messages2 = messages2(messagesRef.current);
310
- }
311
- const messagesWithParts = (0, import_ai2.fillMessageParts)(messages2);
312
- mutate(messagesWithParts, false);
313
- messagesRef.current = messagesWithParts;
314
- },
315
- [mutate]
198
+ const status = (0, import_react.useSyncExternalStore)(
199
+ chatRef.current["~registerStatusCallback"],
200
+ () => chatRef.current.status,
201
+ () => chatRef.current.status
316
202
  );
317
- const setData = (0, import_react2.useCallback)(
318
- (data) => {
319
- if (typeof data === "function") {
320
- data = data(streamDataRef.current);
321
- }
322
- mutateStreamData(data, false);
323
- streamDataRef.current = data;
324
- },
325
- [mutateStreamData]
203
+ const error = (0, import_react.useSyncExternalStore)(
204
+ chatRef.current["~registerErrorCallback"],
205
+ () => chatRef.current.error,
206
+ () => chatRef.current.error
326
207
  );
327
- const [input, setInput] = (0, import_react2.useState)(initialInput);
328
- const handleSubmit = (0, import_react2.useCallback)(
329
- async (event, options = {}, metadata) => {
330
- var _a;
331
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
332
- if (!input && !options.allowEmptySubmit)
333
- return;
334
- if (metadata) {
335
- extraMetadataRef.current = {
336
- ...extraMetadataRef.current,
337
- ...metadata
338
- };
208
+ const setMessages = (0, import_react.useCallback)(
209
+ (messagesParam) => {
210
+ if (typeof messagesParam === "function") {
211
+ messagesParam = messagesParam(chatRef.current.messages);
339
212
  }
340
- const attachmentsForRequest = await (0, import_ai2.prepareAttachmentsForRequest)(
341
- options.experimental_attachments
342
- );
343
- const messages2 = messagesRef.current.concat({
344
- id: generateId(),
345
- createdAt: /* @__PURE__ */ new Date(),
346
- role: "user",
347
- content: input,
348
- experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
349
- parts: [{ type: "text", text: input }]
350
- });
351
- const chatRequest = {
352
- messages: messages2,
353
- headers: options.headers,
354
- body: options.body,
355
- data: options.data
356
- };
357
- triggerRequest(chatRequest);
358
- setInput("");
213
+ chatRef.current.messages = messagesParam;
359
214
  },
360
- [input, generateId, triggerRequest]
361
- );
362
- const handleInputChange = (e) => {
363
- setInput(e.target.value);
364
- };
365
- const addToolResult = (0, import_react2.useCallback)(
366
- ({ toolCallId, result }) => {
367
- const currentMessages = messagesRef.current;
368
- (0, import_ai2.updateToolCallResult)({
369
- messages: currentMessages,
370
- toolCallId,
371
- toolResult: result
372
- });
373
- mutate(
374
- [
375
- ...currentMessages.slice(0, currentMessages.length - 1),
376
- { ...currentMessages[currentMessages.length - 1] }
377
- ],
378
- false
379
- );
380
- if (status === "submitted" || status === "streaming") {
381
- return;
382
- }
383
- const lastMessage = currentMessages[currentMessages.length - 1];
384
- if ((0, import_ai2.isAssistantMessageWithCompletedToolCalls)(lastMessage)) {
385
- triggerRequest({ messages: currentMessages });
386
- }
387
- },
388
- [mutate, status, triggerRequest]
215
+ [chatRef]
389
216
  );
217
+ (0, import_react.useEffect)(() => {
218
+ if (resume) {
219
+ chatRef.current.resumeStream();
220
+ }
221
+ }, [resume, chatRef]);
390
222
  return {
391
- messages: messages != null ? messages : [],
392
- id: chatId,
223
+ id: chatRef.current.id,
224
+ messages,
393
225
  setMessages,
394
- data: streamData,
395
- setData,
226
+ sendMessage: chatRef.current.sendMessage,
227
+ regenerate: chatRef.current.regenerate,
228
+ clearError: chatRef.current.clearError,
229
+ stop: chatRef.current.stop,
396
230
  error,
397
- append,
398
- reload,
399
- stop,
400
- input,
401
- setInput,
402
- handleInputChange,
403
- handleSubmit,
404
- isLoading: status === "submitted" || status === "streaming",
231
+ resumeStream: chatRef.current.resumeStream,
405
232
  status,
406
- addToolResult
233
+ addToolResult: chatRef.current.addToolResult
407
234
  };
408
235
  }
409
236
 
410
237
  // src/use-completion.ts
411
- var import_ai3 = require("ai");
412
- var import_react3 = require("react");
413
- var import_swr2 = __toESM(require("swr"));
238
+ var import_ai2 = require("ai");
239
+ var import_react2 = require("react");
240
+ var import_swr = __toESM(require("swr"));
414
241
  function useCompletion({
415
242
  api = "/api/completion",
416
243
  id,
@@ -421,38 +248,36 @@ function useCompletion({
421
248
  body,
422
249
  streamProtocol = "data",
423
250
  fetch: fetch2,
424
- onResponse,
425
251
  onFinish,
426
252
  onError,
427
253
  experimental_throttle: throttleWaitMs
428
254
  } = {}) {
429
- const hookId = (0, import_react3.useId)();
255
+ const hookId = (0, import_react2.useId)();
430
256
  const completionId = id || hookId;
431
- const { data, mutate } = (0, import_swr2.default)([api, completionId], null, {
257
+ const { data, mutate } = (0, import_swr.default)([api, completionId], null, {
432
258
  fallbackData: initialCompletion
433
259
  });
434
- const { data: isLoading = false, mutate: mutateLoading } = (0, import_swr2.default)(
260
+ const { data: isLoading = false, mutate: mutateLoading } = (0, import_swr.default)(
435
261
  [completionId, "loading"],
436
262
  null
437
263
  );
438
- const { data: streamData, mutate: mutateStreamData } = (0, import_swr2.default)([completionId, "streamData"], null);
439
- const [error, setError] = (0, import_react3.useState)(void 0);
264
+ const [error, setError] = (0, import_react2.useState)(void 0);
440
265
  const completion = data;
441
- const [abortController, setAbortController] = (0, import_react3.useState)(null);
442
- const extraMetadataRef = (0, import_react3.useRef)({
266
+ const [abortController, setAbortController] = (0, import_react2.useState)(null);
267
+ const extraMetadataRef = (0, import_react2.useRef)({
443
268
  credentials,
444
269
  headers,
445
270
  body
446
271
  });
447
- (0, import_react3.useEffect)(() => {
272
+ (0, import_react2.useEffect)(() => {
448
273
  extraMetadataRef.current = {
449
274
  credentials,
450
275
  headers,
451
276
  body
452
277
  };
453
278
  }, [credentials, headers, body]);
454
- const triggerRequest = (0, import_react3.useCallback)(
455
- async (prompt, options) => (0, import_ai3.callCompletionApi)({
279
+ const triggerRequest = (0, import_react2.useCallback)(
280
+ async (prompt, options) => (0, import_ai2.callCompletionApi)({
456
281
  api,
457
282
  prompt,
458
283
  credentials: extraMetadataRef.current.credentials,
@@ -468,14 +293,9 @@ function useCompletion({
468
293
  (completion2) => mutate(completion2, false),
469
294
  throttleWaitMs
470
295
  ),
471
- onData: throttle(
472
- (data2) => mutateStreamData([...streamData != null ? streamData : [], ...data2 != null ? data2 : []], false),
473
- throttleWaitMs
474
- ),
475
296
  setLoading: mutateLoading,
476
297
  setError,
477
298
  setAbortController,
478
- onResponse,
479
299
  onFinish,
480
300
  onError
481
301
  }),
@@ -485,37 +305,34 @@ function useCompletion({
485
305
  api,
486
306
  extraMetadataRef,
487
307
  setAbortController,
488
- onResponse,
489
308
  onFinish,
490
309
  onError,
491
310
  setError,
492
- streamData,
493
311
  streamProtocol,
494
312
  fetch2,
495
- mutateStreamData,
496
313
  throttleWaitMs
497
314
  ]
498
315
  );
499
- const stop = (0, import_react3.useCallback)(() => {
316
+ const stop = (0, import_react2.useCallback)(() => {
500
317
  if (abortController) {
501
318
  abortController.abort();
502
319
  setAbortController(null);
503
320
  }
504
321
  }, [abortController]);
505
- const setCompletion = (0, import_react3.useCallback)(
322
+ const setCompletion = (0, import_react2.useCallback)(
506
323
  (completion2) => {
507
324
  mutate(completion2, false);
508
325
  },
509
326
  [mutate]
510
327
  );
511
- const complete = (0, import_react3.useCallback)(
328
+ const complete = (0, import_react2.useCallback)(
512
329
  async (prompt, options) => {
513
330
  return triggerRequest(prompt, options);
514
331
  },
515
332
  [triggerRequest]
516
333
  );
517
- const [input, setInput] = (0, import_react3.useState)(initialInput);
518
- const handleSubmit = (0, import_react3.useCallback)(
334
+ const [input, setInput] = (0, import_react2.useState)(initialInput);
335
+ const handleSubmit = (0, import_react2.useCallback)(
519
336
  (event) => {
520
337
  var _a;
521
338
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
@@ -523,7 +340,7 @@ function useCompletion({
523
340
  },
524
341
  [input, complete]
525
342
  );
526
- const handleInputChange = (0, import_react3.useCallback)(
343
+ const handleInputChange = (0, import_react2.useCallback)(
527
344
  (e) => {
528
345
  setInput(e.target.value);
529
346
  },
@@ -539,16 +356,15 @@ function useCompletion({
539
356
  setInput,
540
357
  handleInputChange,
541
358
  handleSubmit,
542
- isLoading,
543
- data: streamData
359
+ isLoading
544
360
  };
545
361
  }
546
362
 
547
363
  // src/use-object.ts
548
364
  var import_provider_utils = require("@ai-sdk/provider-utils");
549
- var import_ai4 = require("ai");
550
- var import_react4 = require("react");
551
- var import_swr3 = __toESM(require("swr"));
365
+ var import_ai3 = require("ai");
366
+ var import_react3 = require("react");
367
+ var import_swr2 = __toESM(require("swr"));
552
368
  var getOriginalFetch = () => fetch;
553
369
  function useObject({
554
370
  api,
@@ -562,17 +378,17 @@ function useObject({
562
378
  headers,
563
379
  credentials
564
380
  }) {
565
- const hookId = (0, import_react4.useId)();
381
+ const hookId = (0, import_react3.useId)();
566
382
  const completionId = id != null ? id : hookId;
567
- const { data, mutate } = (0, import_swr3.default)(
383
+ const { data, mutate } = (0, import_swr2.default)(
568
384
  [api, completionId],
569
385
  null,
570
386
  { fallbackData: initialValue }
571
387
  );
572
- const [error, setError] = (0, import_react4.useState)(void 0);
573
- const [isLoading, setIsLoading] = (0, import_react4.useState)(false);
574
- const abortControllerRef = (0, import_react4.useRef)(null);
575
- const stop = (0, import_react4.useCallback)(() => {
388
+ const [error, setError] = (0, import_react3.useState)(void 0);
389
+ const [isLoading, setIsLoading] = (0, import_react3.useState)(false);
390
+ const abortControllerRef = (0, import_react3.useRef)(null);
391
+ const stop = (0, import_react3.useCallback)(() => {
576
392
  var _a;
577
393
  try {
578
394
  (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
@@ -585,9 +401,8 @@ function useObject({
585
401
  const submit = async (input) => {
586
402
  var _a;
587
403
  try {
588
- mutate(void 0);
404
+ clearObject();
589
405
  setIsLoading(true);
590
- setError(void 0);
591
406
  const abortController = new AbortController();
592
407
  abortControllerRef.current = abortController;
593
408
  const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
@@ -613,22 +428,22 @@ function useObject({
613
428
  let latestObject = void 0;
614
429
  await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
615
430
  new WritableStream({
616
- write(chunk) {
431
+ async write(chunk) {
617
432
  accumulatedText += chunk;
618
- const { value } = (0, import_ai4.parsePartialJson)(accumulatedText);
433
+ const { value } = await (0, import_ai3.parsePartialJson)(accumulatedText);
619
434
  const currentObject = value;
620
- if (!(0, import_ai4.isDeepEqualData)(latestObject, currentObject)) {
435
+ if (!(0, import_ai3.isDeepEqualData)(latestObject, currentObject)) {
621
436
  latestObject = currentObject;
622
437
  mutate(currentObject);
623
438
  }
624
439
  },
625
- close() {
440
+ async close() {
626
441
  setIsLoading(false);
627
442
  abortControllerRef.current = null;
628
443
  if (onFinish != null) {
629
- const validationResult = (0, import_provider_utils.safeValidateTypes)({
444
+ const validationResult = await (0, import_provider_utils.safeValidateTypes)({
630
445
  value: latestObject,
631
- schema: (0, import_ai4.asSchema)(schema)
446
+ schema: (0, import_ai3.asSchema)(schema)
632
447
  });
633
448
  onFinish(
634
449
  validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }
@@ -648,17 +463,28 @@ function useObject({
648
463
  setError(error2 instanceof Error ? error2 : new Error(String(error2)));
649
464
  }
650
465
  };
466
+ const clear = () => {
467
+ stop();
468
+ clearObject();
469
+ };
470
+ const clearObject = () => {
471
+ setError(void 0);
472
+ setIsLoading(false);
473
+ mutate(void 0);
474
+ };
651
475
  return {
652
476
  submit,
653
477
  object: data,
654
478
  error,
655
479
  isLoading,
656
- stop
480
+ stop,
481
+ clear
657
482
  };
658
483
  }
659
484
  var experimental_useObject = useObject;
660
485
  // Annotate the CommonJS export names for ESM import in node:
661
486
  0 && (module.exports = {
487
+ Chat,
662
488
  experimental_useObject,
663
489
  useChat,
664
490
  useCompletion