@ai-sdk/react 2.0.0-canary.2 → 2.0.0-canary.4
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 +18 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +21 -21
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @ai-sdk/react
|
|
2
2
|
|
|
3
|
+
## 2.0.0-canary.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [b71fe8d]
|
|
8
|
+
- Updated dependencies [d91b50d]
|
|
9
|
+
- ai@5.0.0-canary.5
|
|
10
|
+
- @ai-sdk/provider-utils@3.0.0-canary.4
|
|
11
|
+
|
|
12
|
+
## 2.0.0-canary.3
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- Updated dependencies [a166433]
|
|
17
|
+
- Updated dependencies [9f95b35]
|
|
18
|
+
- @ai-sdk/provider-utils@3.0.0-canary.3
|
|
19
|
+
- @ai-sdk/ui-utils@2.0.0-canary.3
|
|
20
|
+
|
|
3
21
|
## 2.0.0-canary.2
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from '
|
|
2
|
-
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '
|
|
1
|
+
import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
|
|
2
|
+
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from 'ai';
|
|
3
3
|
import { FetchFunction } from '@ai-sdk/provider-utils';
|
|
4
4
|
import z from 'zod';
|
|
5
5
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from '
|
|
2
|
-
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '
|
|
1
|
+
import { UIMessage, Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, Schema, DeepPartial } from 'ai';
|
|
2
|
+
export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from 'ai';
|
|
3
3
|
import { FetchFunction } from '@ai-sdk/provider-utils';
|
|
4
4
|
import z from 'zod';
|
|
5
5
|
|
package/dist/index.js
CHANGED
|
@@ -37,7 +37,7 @@ __export(src_exports, {
|
|
|
37
37
|
module.exports = __toCommonJS(src_exports);
|
|
38
38
|
|
|
39
39
|
// src/use-chat.ts
|
|
40
|
-
var
|
|
40
|
+
var import_ai2 = require("ai");
|
|
41
41
|
var import_react2 = require("react");
|
|
42
42
|
var import_swr = __toESM(require("swr"));
|
|
43
43
|
|
|
@@ -48,12 +48,12 @@ function throttle(fn, waitMs) {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
// src/util/use-stable-value.ts
|
|
51
|
-
var
|
|
51
|
+
var import_ai = require("ai");
|
|
52
52
|
var import_react = require("react");
|
|
53
53
|
function useStableValue(latestValue) {
|
|
54
54
|
const [value, setValue] = (0, import_react.useState)(latestValue);
|
|
55
55
|
(0, import_react.useEffect)(() => {
|
|
56
|
-
if (!(0,
|
|
56
|
+
if (!(0, import_ai.isDeepEqualData)(latestValue, value)) {
|
|
57
57
|
setValue(latestValue);
|
|
58
58
|
}
|
|
59
59
|
}, [latestValue, value]);
|
|
@@ -77,7 +77,7 @@ function useChat({
|
|
|
77
77
|
credentials,
|
|
78
78
|
headers,
|
|
79
79
|
body,
|
|
80
|
-
generateId =
|
|
80
|
+
generateId = import_ai2.generateId,
|
|
81
81
|
fetch: fetch2,
|
|
82
82
|
keepLastMessageOnError = true,
|
|
83
83
|
experimental_throttle: throttleWaitMs
|
|
@@ -87,7 +87,7 @@ function useChat({
|
|
|
87
87
|
const chatKey = typeof api === "string" ? [api, chatId] : chatId;
|
|
88
88
|
const stableInitialMessages = useStableValue(initialMessages != null ? initialMessages : []);
|
|
89
89
|
const processedInitialMessages = (0, import_react2.useMemo)(
|
|
90
|
-
() => (0,
|
|
90
|
+
() => (0, import_ai2.fillMessageParts)(stableInitialMessages),
|
|
91
91
|
[stableInitialMessages]
|
|
92
92
|
);
|
|
93
93
|
const { data: messages, mutate } = (0, import_swr.default)(
|
|
@@ -124,9 +124,9 @@ function useChat({
|
|
|
124
124
|
var _a, _b;
|
|
125
125
|
mutateStatus("submitted");
|
|
126
126
|
setError(void 0);
|
|
127
|
-
const chatMessages = (0,
|
|
127
|
+
const chatMessages = (0, import_ai2.fillMessageParts)(chatRequest.messages);
|
|
128
128
|
const messageCount = chatMessages.length;
|
|
129
|
-
const maxStep = (0,
|
|
129
|
+
const maxStep = (0, import_ai2.extractMaxToolInvocationStep)(
|
|
130
130
|
(_a = chatMessages[chatMessages.length - 1]) == null ? void 0 : _a.toolInvocations
|
|
131
131
|
);
|
|
132
132
|
try {
|
|
@@ -161,7 +161,7 @@ function useChat({
|
|
|
161
161
|
})
|
|
162
162
|
);
|
|
163
163
|
const existingData = streamDataRef.current;
|
|
164
|
-
await (0,
|
|
164
|
+
await (0, import_ai2.callChatApi)({
|
|
165
165
|
api,
|
|
166
166
|
body: (_b = experimental_prepareRequestBody == null ? void 0 : experimental_prepareRequestBody({
|
|
167
167
|
id: chatId,
|
|
@@ -225,7 +225,7 @@ function useChat({
|
|
|
225
225
|
mutateStatus("error");
|
|
226
226
|
}
|
|
227
227
|
const messages2 = messagesRef.current;
|
|
228
|
-
if ((0,
|
|
228
|
+
if ((0, import_ai2.shouldResubmitMessages)({
|
|
229
229
|
originalMaxToolInvocationStep: maxStep,
|
|
230
230
|
originalMessageCount: messageCount,
|
|
231
231
|
maxSteps,
|
|
@@ -267,7 +267,7 @@ function useChat({
|
|
|
267
267
|
experimental_attachments
|
|
268
268
|
} = {}) => {
|
|
269
269
|
var _a, _b;
|
|
270
|
-
const attachmentsForRequest = await (0,
|
|
270
|
+
const attachmentsForRequest = await (0, import_ai2.prepareAttachmentsForRequest)(
|
|
271
271
|
experimental_attachments
|
|
272
272
|
);
|
|
273
273
|
const messages2 = messagesRef.current.concat({
|
|
@@ -275,7 +275,7 @@ function useChat({
|
|
|
275
275
|
id: (_a = message.id) != null ? _a : generateId(),
|
|
276
276
|
createdAt: (_b = message.createdAt) != null ? _b : /* @__PURE__ */ new Date(),
|
|
277
277
|
experimental_attachments: attachmentsForRequest.length > 0 ? attachmentsForRequest : void 0,
|
|
278
|
-
parts: (0,
|
|
278
|
+
parts: (0, import_ai2.getMessageParts)(message)
|
|
279
279
|
});
|
|
280
280
|
return triggerRequest({ messages: messages2, headers: headers2, body: body2, data });
|
|
281
281
|
},
|
|
@@ -308,7 +308,7 @@ function useChat({
|
|
|
308
308
|
if (typeof messages2 === "function") {
|
|
309
309
|
messages2 = messages2(messagesRef.current);
|
|
310
310
|
}
|
|
311
|
-
const messagesWithParts = (0,
|
|
311
|
+
const messagesWithParts = (0, import_ai2.fillMessageParts)(messages2);
|
|
312
312
|
mutate(messagesWithParts, false);
|
|
313
313
|
messagesRef.current = messagesWithParts;
|
|
314
314
|
},
|
|
@@ -337,7 +337,7 @@ function useChat({
|
|
|
337
337
|
...metadata
|
|
338
338
|
};
|
|
339
339
|
}
|
|
340
|
-
const attachmentsForRequest = await (0,
|
|
340
|
+
const attachmentsForRequest = await (0, import_ai2.prepareAttachmentsForRequest)(
|
|
341
341
|
options.experimental_attachments
|
|
342
342
|
);
|
|
343
343
|
const messages2 = messagesRef.current.concat({
|
|
@@ -365,7 +365,7 @@ function useChat({
|
|
|
365
365
|
const addToolResult = (0, import_react2.useCallback)(
|
|
366
366
|
({ toolCallId, result }) => {
|
|
367
367
|
const currentMessages = messagesRef.current;
|
|
368
|
-
(0,
|
|
368
|
+
(0, import_ai2.updateToolCallResult)({
|
|
369
369
|
messages: currentMessages,
|
|
370
370
|
toolCallId,
|
|
371
371
|
toolResult: result
|
|
@@ -381,7 +381,7 @@ function useChat({
|
|
|
381
381
|
return;
|
|
382
382
|
}
|
|
383
383
|
const lastMessage = currentMessages[currentMessages.length - 1];
|
|
384
|
-
if ((0,
|
|
384
|
+
if ((0, import_ai2.isAssistantMessageWithCompletedToolCalls)(lastMessage)) {
|
|
385
385
|
triggerRequest({ messages: currentMessages });
|
|
386
386
|
}
|
|
387
387
|
},
|
|
@@ -408,7 +408,7 @@ function useChat({
|
|
|
408
408
|
}
|
|
409
409
|
|
|
410
410
|
// src/use-completion.ts
|
|
411
|
-
var
|
|
411
|
+
var import_ai3 = require("ai");
|
|
412
412
|
var import_react3 = require("react");
|
|
413
413
|
var import_swr2 = __toESM(require("swr"));
|
|
414
414
|
function useCompletion({
|
|
@@ -452,7 +452,7 @@ function useCompletion({
|
|
|
452
452
|
};
|
|
453
453
|
}, [credentials, headers, body]);
|
|
454
454
|
const triggerRequest = (0, import_react3.useCallback)(
|
|
455
|
-
async (prompt, options) => (0,
|
|
455
|
+
async (prompt, options) => (0, import_ai3.callCompletionApi)({
|
|
456
456
|
api,
|
|
457
457
|
prompt,
|
|
458
458
|
credentials: extraMetadataRef.current.credentials,
|
|
@@ -546,7 +546,7 @@ function useCompletion({
|
|
|
546
546
|
|
|
547
547
|
// src/use-object.ts
|
|
548
548
|
var import_provider_utils = require("@ai-sdk/provider-utils");
|
|
549
|
-
var
|
|
549
|
+
var import_ai4 = require("ai");
|
|
550
550
|
var import_react4 = require("react");
|
|
551
551
|
var import_swr3 = __toESM(require("swr"));
|
|
552
552
|
var getOriginalFetch = () => fetch;
|
|
@@ -615,9 +615,9 @@ function useObject({
|
|
|
615
615
|
new WritableStream({
|
|
616
616
|
write(chunk) {
|
|
617
617
|
accumulatedText += chunk;
|
|
618
|
-
const { value } = (0,
|
|
618
|
+
const { value } = (0, import_ai4.parsePartialJson)(accumulatedText);
|
|
619
619
|
const currentObject = value;
|
|
620
|
-
if (!(0,
|
|
620
|
+
if (!(0, import_ai4.isDeepEqualData)(latestObject, currentObject)) {
|
|
621
621
|
latestObject = currentObject;
|
|
622
622
|
mutate(currentObject);
|
|
623
623
|
}
|
|
@@ -628,7 +628,7 @@ function useObject({
|
|
|
628
628
|
if (onFinish != null) {
|
|
629
629
|
const validationResult = (0, import_provider_utils.safeValidateTypes)({
|
|
630
630
|
value: latestObject,
|
|
631
|
-
schema: (0,
|
|
631
|
+
schema: (0, import_ai4.asSchema)(schema)
|
|
632
632
|
});
|
|
633
633
|
onFinish(
|
|
634
634
|
validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\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: Message[] | ((messages: Message[]) => Message[]),\n ) => 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 /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls.\nMust be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => fillMessageParts(stableInitialMessages),\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<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 (chatRequest: ChatRequest) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = fillMessageParts(chatRequest.messages);\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n chatMessages[chatMessages.length - 1]?.toolInvocations,\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n throttledMutate(chatMessages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n throttledMutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n });\n\n return triggerRequest({ messages, headers, body, data });\n },\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n const messagesWithParts = fillMessageParts(messages);\n mutate(messagesWithParts, false);\n messagesRef.current = messagesWithParts;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: input }],\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n { ...currentMessages[currentMessages.length - 1] },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\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 { isDeepEqualData } from '@ai-sdk/ui-utils';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data?: JSONValue[];\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 onResponse,\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 { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\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?: RequestOptions) =>\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 onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\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 data: streamData,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\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: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\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\nfunction useObject<RESULT, INPUT = any>({\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<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\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 mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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 return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,IAAAA,mBAUO;AACP,IAAAC,gBAAkE;AAClE,iBAAmB;;;ACrBnB,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAC,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,sBAAgC;AAChC,mBAAoC;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAY,WAAW;AAEjD,8BAAU,MAAM;AACd,QAAI,K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,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,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,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["import_ui_utils","import_react","throttleFunction","generateIdFunc","fetch","useSWR","messages","headers","body","import_ui_utils","import_react","import_swr","fetch","useSWR","completion","data","import_ui_utils","import_react","import_swr","fetch","useSWR","error"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport * from './use-completion';\nexport * from './use-object';\n","import type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\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: Message[] | ((messages: Message[]) => Message[]),\n ) => 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 /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls.\nMust be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => fillMessageParts(stableInitialMessages),\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<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 (chatRequest: ChatRequest) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = fillMessageParts(chatRequest.messages);\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n chatMessages[chatMessages.length - 1]?.toolInvocations,\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n throttledMutate(chatMessages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n throttledMutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n });\n\n return triggerRequest({ messages, headers, body, data });\n },\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n const messagesWithParts = fillMessageParts(messages);\n mutate(messagesWithParts, false);\n messagesRef.current = messagesWithParts;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: input }],\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n { ...currentMessages[currentMessages.length - 1] },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\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 { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n JSONValue,\n RequestOptions,\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data?: JSONValue[];\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 onResponse,\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 { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\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?: RequestOptions) =>\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 onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\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 data: streamData,\n };\n}\n","import {\n FetchFunction,\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 z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\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: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\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\nfunction useObject<RESULT, INPUT = any>({\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<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\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 mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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 return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,IAAAA,aAUO;AACP,IAAAC,gBAAkE;AAClE,iBAAmB;;;ACrBnB,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAC,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,gBAAgC;AAChC,mBAAoC;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAY,WAAW;AAEjD,8BAAU,MAAM;AACd,QAAI,KAAC,2BAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GA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M;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,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,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["import_ai","import_react","throttleFunction","generateIdFunc","fetch","useSWR","messages","headers","body","import_ai","import_react","import_swr","fetch","useSWR","completion","data","import_ai","import_react","import_swr","fetch","useSWR","error"]}
|
package/dist/index.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
prepareAttachmentsForRequest,
|
|
10
10
|
shouldResubmitMessages,
|
|
11
11
|
updateToolCallResult
|
|
12
|
-
} from "
|
|
12
|
+
} from "ai";
|
|
13
13
|
import { useCallback, useEffect as useEffect2, useMemo, useRef, useState as useState2 } from "react";
|
|
14
14
|
import useSWR from "swr";
|
|
15
15
|
|
|
@@ -20,7 +20,7 @@ function throttle(fn, waitMs) {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
// src/util/use-stable-value.ts
|
|
23
|
-
import { isDeepEqualData } from "
|
|
23
|
+
import { isDeepEqualData } from "ai";
|
|
24
24
|
import { useEffect, useState } from "react";
|
|
25
25
|
function useStableValue(latestValue) {
|
|
26
26
|
const [value, setValue] = useState(latestValue);
|
|
@@ -382,7 +382,7 @@ function useChat({
|
|
|
382
382
|
// src/use-completion.ts
|
|
383
383
|
import {
|
|
384
384
|
callCompletionApi
|
|
385
|
-
} from "
|
|
385
|
+
} from "ai";
|
|
386
386
|
import { useCallback as useCallback2, useEffect as useEffect3, useId, useRef as useRef2, useState as useState3 } from "react";
|
|
387
387
|
import useSWR2 from "swr";
|
|
388
388
|
function useCompletion({
|
|
@@ -527,7 +527,7 @@ import {
|
|
|
527
527
|
asSchema,
|
|
528
528
|
isDeepEqualData as isDeepEqualData2,
|
|
529
529
|
parsePartialJson
|
|
530
|
-
} from "
|
|
530
|
+
} from "ai";
|
|
531
531
|
import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState4 } from "react";
|
|
532
532
|
import useSWR3 from "swr";
|
|
533
533
|
var getOriginalFetch = () => fetch;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from '@ai-sdk/ui-utils';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\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: Message[] | ((messages: Message[]) => Message[]),\n ) => 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 /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls.\nMust be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => fillMessageParts(stableInitialMessages),\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<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 (chatRequest: ChatRequest) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = fillMessageParts(chatRequest.messages);\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n chatMessages[chatMessages.length - 1]?.toolInvocations,\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n throttledMutate(chatMessages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n throttledMutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n });\n\n return triggerRequest({ messages, headers, body, data });\n },\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n const messagesWithParts = fillMessageParts(messages);\n mutate(messagesWithParts, false);\n messagesRef.current = messagesWithParts;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: input }],\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n { ...currentMessages[currentMessages.length - 1] },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\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 { isDeepEqualData } from '@ai-sdk/ui-utils';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n JSONValue,\n RequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from '@ai-sdk/ui-utils';\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data?: JSONValue[];\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 onResponse,\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 { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\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?: RequestOptions) =>\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 onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\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 data: streamData,\n };\n}\n","import {\n FetchFunction,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n DeepPartial,\n isDeepEqualData,\n parsePartialJson,\n Schema,\n} from '@ai-sdk/ui-utils';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\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: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\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\nfunction useObject<RESULT, INPUT = any>({\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<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\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 mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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 return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAAA,YAAW,SAAS,QAAQ,YAAAC,iBAAgB;AAClE,OAAO,YAAY;;;ACrBnB,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,SAAS,uBAAuB;AAChC,SAAS,WAAW,gBAAgB;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,WAAW;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,gBAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,aAAa,KAAK,CAAC;AAEvB,SAAO;AACT;;;AF8FO,SAAS,QAAQ;AAAA,EACtB,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,eAAe;AAAA,EACf;AAAA,EACA;AAA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AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASO,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,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useEffect","useState","fetch","useState","useEffect","messages","headers","body","useCallback","useEffect","useRef","useState","useSWR","fetch","useSWR","useState","useRef","useEffect","useCallback","completion","data","isDeepEqualData","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
|
|
1
|
+
{"version":3,"sources":["../src/use-chat.ts","../src/throttle.ts","../src/util/use-stable-value.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import type {\n ChatRequest,\n ChatRequestOptions,\n CreateMessage,\n JSONValue,\n Message,\n UIMessage,\n UseChatOptions,\n} from 'ai';\nimport {\n callChatApi,\n extractMaxToolInvocationStep,\n fillMessageParts,\n generateId as generateIdFunc,\n getMessageParts,\n isAssistantMessageWithCompletedToolCalls,\n prepareAttachmentsForRequest,\n shouldResubmitMessages,\n updateToolCallResult,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\nimport { useStableValue } from './util/use-stable-value';\n\nexport type { CreateMessage, Message, UseChatOptions };\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: UIMessage[];\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n * @param options Additional options to pass to the API call\n */\n append: (\n message: Message | CreateMessage,\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: (\n chatRequestOptions?: ChatRequestOptions,\n ) => Promise<string | null | undefined>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\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: Message[] | ((messages: Message[]) => Message[]),\n ) => 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 /** An input/textarea-ready onChange handler to control the value of the input */\n handleInputChange: (\n e:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n /** Form submission handler to automatically reset input and append a user message */\n handleSubmit: (\n event?: { preventDefault?: () => void },\n chatRequestOptions?: ChatRequestOptions,\n ) => void;\n metadata?: Object;\n\n /**\n * Whether the API request is in progress\n *\n * @deprecated use `status` instead\n */\n isLoading: boolean;\n\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n status: 'submitted' | 'streaming' | 'ready' | 'error';\n\n /** Additional data added on the server via StreamData. */\n data?: JSONValue[];\n\n /** Set the data of the chat. You can use this to transform or clear the chat data. */\n setData: (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => void;\n\n /** The id of the chat */\n id: string;\n};\n\nexport function useChat({\n api = '/api/chat',\n id,\n initialMessages,\n initialInput = '',\n sendExtraMessageFields,\n onToolCall,\n experimental_prepareRequestBody,\n maxSteps = 1,\n streamProtocol = 'data',\n onResponse,\n onFinish,\n onError,\n credentials,\n headers,\n body,\n generateId = generateIdFunc,\n fetch,\n keepLastMessageOnError = true,\n experimental_throttle: throttleWaitMs,\n}: UseChatOptions & {\n key?: string;\n\n /**\n * Experimental (React only). When a function is provided, it will be used\n * to prepare the request body for the chat API. This can be useful for\n * customizing the request body based on the messages and data in the chat.\n *\n * @param messages The current messages in the chat.\n * @param requestData The data object passed in the chat request.\n * @param requestBody The request body object passed in the chat request.\n */\n experimental_prepareRequestBody?: (options: {\n id: string;\n messages: UIMessage[];\n requestData?: JSONValue;\n requestBody?: object;\n }) => unknown;\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 /**\nMaximum number of sequential LLM calls (steps), e.g. when you use tool calls.\nMust be at least 1.\n\nA maximum number is required to prevent infinite loops in the case of misconfigured tools.\n\nBy default, it's set to 1, which means that only a single LLM call is made.\n */\n maxSteps?: number;\n} = {}): UseChatHelpers & {\n addToolResult: ({\n toolCallId,\n result,\n }: {\n toolCallId: string;\n result: any;\n }) => void;\n} {\n // Generate ID once, store in state for stability across re-renders\n const [hookId] = useState(generateId);\n\n // Use the caller-supplied ID if available; otherwise, fall back to our stable ID\n const chatId = id ?? hookId;\n const chatKey = typeof api === 'string' ? [api, chatId] : chatId;\n\n // Store array of the processed initial messages to avoid re-renders:\n const stableInitialMessages = useStableValue(initialMessages ?? []);\n const processedInitialMessages = useMemo(\n () => fillMessageParts(stableInitialMessages),\n [stableInitialMessages],\n );\n\n // Store the chat state in SWR, using the chatId as the key to share states.\n const { data: messages, mutate } = useSWR<UIMessage[]>(\n [chatKey, 'messages'],\n null,\n { fallbackData: processedInitialMessages },\n );\n\n // Keep the latest messages in a ref.\n const messagesRef = useRef<UIMessage[]>(messages || []);\n useEffect(() => {\n messagesRef.current = messages || [];\n }, [messages]);\n\n // stream data\n const { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([chatKey, 'streamData'], null);\n\n // keep the latest stream data in a ref\n const streamDataRef = useRef<JSONValue[] | undefined>(streamData);\n useEffect(() => {\n streamDataRef.current = streamData;\n }, [streamData]);\n\n const { data: status = 'ready', mutate: mutateStatus } = useSWR<\n 'submitted' | 'streaming' | 'ready' | 'error'\n >([chatKey, 'status'], null);\n\n const { data: error = undefined, mutate: setError } = useSWR<\n undefined | Error\n >([chatKey, 'error'], null);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<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 (chatRequest: ChatRequest) => {\n mutateStatus('submitted');\n setError(undefined);\n\n const chatMessages = fillMessageParts(chatRequest.messages);\n\n const messageCount = chatMessages.length;\n const maxStep = extractMaxToolInvocationStep(\n chatMessages[chatMessages.length - 1]?.toolInvocations,\n );\n\n try {\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const throttledMutate = throttle(mutate, throttleWaitMs);\n const throttledMutateStreamData = throttle(\n mutateStreamData,\n throttleWaitMs,\n );\n\n // Do an optimistic update to the chat state to show the updated messages immediately:\n const previousMessages = messagesRef.current;\n throttledMutate(chatMessages, false);\n\n const constructedMessagesPayload = sendExtraMessageFields\n ? chatMessages\n : chatMessages.map(\n ({\n role,\n content,\n experimental_attachments,\n data,\n annotations,\n toolInvocations,\n parts,\n }) => ({\n role,\n content,\n ...(experimental_attachments !== undefined && {\n experimental_attachments,\n }),\n ...(data !== undefined && { data }),\n ...(annotations !== undefined && { annotations }),\n ...(toolInvocations !== undefined && { toolInvocations }),\n ...(parts !== undefined && { parts }),\n }),\n );\n\n const existingData = streamDataRef.current;\n\n await callChatApi({\n api,\n body: experimental_prepareRequestBody?.({\n id: chatId,\n messages: chatMessages,\n requestData: chatRequest.data,\n requestBody: chatRequest.body,\n }) ?? {\n id: chatId,\n messages: constructedMessagesPayload,\n data: chatRequest.data,\n ...extraMetadataRef.current.body,\n ...chatRequest.body,\n },\n streamProtocol,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...extraMetadataRef.current.headers,\n ...chatRequest.headers,\n },\n abortController: () => abortControllerRef.current,\n restoreMessagesOnFailure() {\n if (!keepLastMessageOnError) {\n throttledMutate(previousMessages, false);\n }\n },\n onResponse,\n onUpdate({ message, data, replaceLastMessage }) {\n mutateStatus('streaming');\n\n throttledMutate(\n [\n ...(replaceLastMessage\n ? chatMessages.slice(0, chatMessages.length - 1)\n : chatMessages),\n message,\n ],\n false,\n );\n\n if (data?.length) {\n throttledMutateStreamData(\n [...(existingData ?? []), ...data],\n false,\n );\n }\n },\n onToolCall,\n onFinish,\n generateId,\n fetch,\n lastMessage: chatMessages[chatMessages.length - 1],\n });\n\n abortControllerRef.current = null;\n\n mutateStatus('ready');\n } catch (err) {\n // Ignore abort errors as they are expected.\n if ((err as any).name === 'AbortError') {\n abortControllerRef.current = null;\n mutateStatus('ready');\n return null;\n }\n\n if (onError && err instanceof Error) {\n onError(err);\n }\n\n setError(err as Error);\n mutateStatus('error');\n }\n\n // auto-submit when all tool calls in the last assistant message have results\n // and assistant has not answered yet\n const messages = messagesRef.current;\n if (\n shouldResubmitMessages({\n originalMaxToolInvocationStep: maxStep,\n originalMessageCount: messageCount,\n maxSteps,\n messages,\n })\n ) {\n await triggerRequest({ messages });\n }\n },\n [\n mutate,\n mutateStatus,\n api,\n extraMetadataRef,\n onResponse,\n onFinish,\n onError,\n setError,\n mutateStreamData,\n streamDataRef,\n streamProtocol,\n sendExtraMessageFields,\n experimental_prepareRequestBody,\n onToolCall,\n maxSteps,\n messagesRef,\n abortControllerRef,\n generateId,\n fetch,\n keepLastMessageOnError,\n throttleWaitMs,\n chatId,\n ],\n );\n\n const append = useCallback(\n async (\n message: Message | CreateMessage,\n {\n data,\n headers,\n body,\n experimental_attachments,\n }: ChatRequestOptions = {},\n ) => {\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n ...message,\n id: message.id ?? generateId(),\n createdAt: message.createdAt ?? new Date(),\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: getMessageParts(message),\n });\n\n return triggerRequest({ messages, headers, body, data });\n },\n [triggerRequest, generateId],\n );\n\n const reload = useCallback(\n async ({ data, headers, body }: ChatRequestOptions = {}) => {\n const messages = messagesRef.current;\n\n if (messages.length === 0) {\n return null;\n }\n\n // Remove last assistant message and retry last user message.\n const lastMessage = messages[messages.length - 1];\n return triggerRequest({\n messages:\n lastMessage.role === 'assistant' ? messages.slice(0, -1) : messages,\n headers,\n body,\n data,\n });\n },\n [triggerRequest],\n );\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n }\n }, []);\n\n const setMessages = useCallback(\n (messages: Message[] | ((messages: Message[]) => Message[])) => {\n if (typeof messages === 'function') {\n messages = messages(messagesRef.current);\n }\n\n const messagesWithParts = fillMessageParts(messages);\n mutate(messagesWithParts, false);\n messagesRef.current = messagesWithParts;\n },\n [mutate],\n );\n\n const setData = useCallback(\n (\n data:\n | JSONValue[]\n | undefined\n | ((data: JSONValue[] | undefined) => JSONValue[] | undefined),\n ) => {\n if (typeof data === 'function') {\n data = data(streamDataRef.current);\n }\n\n mutateStreamData(data, false);\n streamDataRef.current = data;\n },\n [mutateStreamData],\n );\n\n // Input state and handlers.\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n async (\n event?: { preventDefault?: () => void },\n options: ChatRequestOptions = {},\n metadata?: Object,\n ) => {\n event?.preventDefault?.();\n\n if (!input && !options.allowEmptySubmit) return;\n\n if (metadata) {\n extraMetadataRef.current = {\n ...extraMetadataRef.current,\n ...metadata,\n };\n }\n\n const attachmentsForRequest = await prepareAttachmentsForRequest(\n options.experimental_attachments,\n );\n\n const messages = messagesRef.current.concat({\n id: generateId(),\n createdAt: new Date(),\n role: 'user',\n content: input,\n experimental_attachments:\n attachmentsForRequest.length > 0 ? attachmentsForRequest : undefined,\n parts: [{ type: 'text', text: input }],\n });\n\n const chatRequest: ChatRequest = {\n messages,\n headers: options.headers,\n body: options.body,\n data: options.data,\n };\n\n triggerRequest(chatRequest);\n\n setInput('');\n },\n [input, generateId, triggerRequest],\n );\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const addToolResult = useCallback(\n ({ toolCallId, result }: { toolCallId: string; result: unknown }) => {\n const currentMessages = messagesRef.current;\n\n updateToolCallResult({\n messages: currentMessages,\n toolCallId,\n toolResult: result,\n });\n\n // array mutation is required to trigger a re-render\n mutate(\n [\n ...currentMessages.slice(0, currentMessages.length - 1),\n { ...currentMessages[currentMessages.length - 1] },\n ],\n false,\n );\n\n // when the request is ongoing, the auto-submit will be triggered after the request is finished\n if (status === 'submitted' || status === 'streaming') {\n return;\n }\n\n // auto-submit when all tool calls in the last assistant message have results:\n const lastMessage = currentMessages[currentMessages.length - 1];\n if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {\n triggerRequest({ messages: currentMessages });\n }\n },\n [mutate, status, triggerRequest],\n );\n\n return {\n messages: messages ?? [],\n id: chatId,\n setMessages,\n data: streamData,\n setData,\n error,\n append,\n reload,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading: status === 'submitted' || status === 'streaming',\n status,\n addToolResult,\n };\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 { isDeepEqualData } from 'ai';\nimport { useEffect, useState } from 'react';\n\n/**\n * Returns a stable value that only updates the stored value (and triggers a re-render)\n * when the value's contents differ by deep-compare.\n */\nexport function useStableValue<T>(latestValue: T): T {\n const [value, setValue] = useState<T>(latestValue);\n\n useEffect(() => {\n if (!isDeepEqualData(latestValue, value)) {\n setValue(latestValue);\n }\n }, [latestValue, value]);\n\n return value;\n}\n","import {\n JSONValue,\n RequestOptions,\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?: RequestOptions,\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 /** Additional data added on the server via StreamData */\n data?: JSONValue[];\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 onResponse,\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 { data: streamData, mutate: mutateStreamData } = useSWR<\n JSONValue[] | undefined\n >([completionId, 'streamData'], null);\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?: RequestOptions) =>\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 onData: throttle(\n (data: JSONValue[]) =>\n mutateStreamData([...(streamData ?? []), ...(data ?? [])], false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onResponse,\n onFinish,\n onError,\n setError,\n streamData,\n streamProtocol,\n fetch,\n mutateStreamData,\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 data: streamData,\n };\n}\n","import {\n FetchFunction,\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 z from 'zod';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<RESULT> = {\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: z.Schema<RESULT, z.ZodTypeDef, any> | Schema<RESULT>;\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\nfunction useObject<RESULT, INPUT = any>({\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<RESULT>): Experimental_UseObjectHelpers<\n RESULT,\n INPUT\n> {\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 mutate(undefined); // reset the data\n setIsLoading(true);\n setError(undefined);\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 write(chunk) {\n accumulatedText += chunk;\n\n const { value } = 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 close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = 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 return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,aAAAA,YAAW,SAAS,QAAQ,YAAAC,iBAAgB;AAClE,OAAO,YAAY;;;ACrBnB,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ACPA,SAAS,uBAAuB;AAChC,SAAS,WAAW,gBAAgB;AAM7B,SAAS,eAAkB,aAAmB;AACnD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,WAAW;AAEjD,YAAU,MAAM;AACd,QAAI,CAAC,gBAAgB,aAAa,KAAK,GAAG;AACxC,eAAS,WAAW;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,aAAa,KAAK,CAAC;AAEvB,SAAO;AACT;;;AF8FO,SAAS,QA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OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASO,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,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useEffect","useState","fetch","useState","useEffect","messages","headers","body","useCallback","useEffect","useRef","useState","useSWR","fetch","useSWR","useState","useRef","useEffect","useCallback","completion","data","isDeepEqualData","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.0.0-canary.
|
|
3
|
+
"version": "2.0.0-canary.4",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
"CHANGELOG.md"
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"
|
|
23
|
-
"@ai-sdk/
|
|
22
|
+
"ai": "5.0.0-canary.5",
|
|
23
|
+
"@ai-sdk/provider-utils": "3.0.0-canary.4",
|
|
24
24
|
"swr": "^2.2.5",
|
|
25
25
|
"throttleit": "2.1.0"
|
|
26
26
|
},
|