@ai-sdk/react 4.0.0-beta.19 → 4.0.0-beta.190

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/src/use-object.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  import {
2
- FetchFunction,
3
- FlexibleSchema,
4
- InferSchema,
5
2
  isAbortError,
6
- Resolvable,
7
3
  resolve,
8
4
  normalizeHeaders,
9
5
  safeValidateTypes,
6
+ type FetchFunction,
7
+ type FlexibleSchema,
8
+ type InferSchema,
9
+ type Resolvable,
10
10
  } from '@ai-sdk/provider-utils';
11
- import { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';
11
+ import {
12
+ asSchema,
13
+ isDeepEqualData,
14
+ parsePartialJson,
15
+ type DeepPartial,
16
+ } from 'ai';
12
17
  import { useCallback, useId, useRef, useState } from 'react';
13
18
  import useSWR from 'swr';
14
19
 
@@ -153,7 +158,7 @@ function useObject<
153
158
  const stop = useCallback(() => {
154
159
  try {
155
160
  abortControllerRef.current?.abort();
156
- } catch (ignored) {
161
+ } catch {
157
162
  } finally {
158
163
  setIsLoading(false);
159
164
  abortControllerRef.current = null;
@@ -0,0 +1,252 @@
1
+ import {
2
+ Experimental_AbstractRealtimeSession as AbstractRealtimeSession,
3
+ type Experimental_RealtimeServerEvent as RealtimeServerEvent,
4
+ type Experimental_RealtimeSessionOptions as RealtimeSessionOptions,
5
+ type Experimental_RealtimeState as RealtimeState,
6
+ type Experimental_RealtimeStatus as RealtimeStatus,
7
+ type UIMessage,
8
+ } from 'ai';
9
+ import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';
10
+
11
+ type UseRealtimeOptions = RealtimeSessionOptions;
12
+
13
+ type RealtimeStateKey = keyof RealtimeState;
14
+ type RealtimeStoreKey = {
15
+ model: RealtimeSessionOptions['model'];
16
+ token: RealtimeSessionOptions['api']['token'];
17
+ sessionConfig: RealtimeSessionOptions['sessionConfig'];
18
+ sampleRate: RealtimeSessionOptions['sampleRate'];
19
+ maxEvents: RealtimeSessionOptions['maxEvents'];
20
+ };
21
+
22
+ function getRealtimeStoreKey(options: UseRealtimeOptions): RealtimeStoreKey {
23
+ return {
24
+ model: options.model,
25
+ token: options.api.token,
26
+ sessionConfig: options.sessionConfig,
27
+ sampleRate: options.sampleRate,
28
+ maxEvents: options.maxEvents,
29
+ };
30
+ }
31
+
32
+ function shouldCreateRealtimeStore(
33
+ currentKey: RealtimeStoreKey,
34
+ nextOptions: UseRealtimeOptions,
35
+ ): boolean {
36
+ return (
37
+ currentKey.model !== nextOptions.model ||
38
+ currentKey.token !== nextOptions.api.token ||
39
+ currentKey.sessionConfig !== nextOptions.sessionConfig ||
40
+ currentKey.sampleRate !== nextOptions.sampleRate ||
41
+ currentKey.maxEvents !== nextOptions.maxEvents
42
+ );
43
+ }
44
+
45
+ class RealtimeStore extends AbstractRealtimeSession {
46
+ protected state: RealtimeState = {
47
+ status: 'disconnected',
48
+ messages: [],
49
+ events: [],
50
+ isCapturing: false,
51
+ isPlaying: false,
52
+ };
53
+
54
+ private callbacks: { [K in RealtimeStateKey]: Set<() => void> } = {
55
+ status: new Set(),
56
+ messages: new Set(),
57
+ events: new Set(),
58
+ isCapturing: new Set(),
59
+ isPlaying: new Set(),
60
+ };
61
+
62
+ get status(): RealtimeStatus {
63
+ return this.state.status;
64
+ }
65
+
66
+ get messages(): UIMessage[] {
67
+ return this.state.messages;
68
+ }
69
+
70
+ get events(): RealtimeServerEvent[] {
71
+ return this.state.events;
72
+ }
73
+
74
+ get isCapturing(): boolean {
75
+ return this.state.isCapturing;
76
+ }
77
+
78
+ get isPlaying(): boolean {
79
+ return this.state.isPlaying;
80
+ }
81
+
82
+ subscribe(key: RealtimeStateKey, onChange: () => void): () => void {
83
+ this.callbacks[key].add(onChange);
84
+
85
+ return () => {
86
+ this.callbacks[key].delete(onChange);
87
+ };
88
+ }
89
+
90
+ protected setState<K extends RealtimeStateKey>(
91
+ key: K,
92
+ value: RealtimeState[K],
93
+ ): void {
94
+ this.state = { ...this.state, [key]: value };
95
+ this.callbacks[key].forEach(callback => callback());
96
+ }
97
+
98
+ protected pushMessage(message: UIMessage): void {
99
+ this.state = {
100
+ ...this.state,
101
+ messages: [...this.state.messages, message],
102
+ };
103
+ this.callbacks.messages.forEach(callback => callback());
104
+ }
105
+
106
+ protected updateMessages(
107
+ updater: (messages: UIMessage[]) => UIMessage[],
108
+ ): void {
109
+ this.state = {
110
+ ...this.state,
111
+ messages: updater(this.state.messages),
112
+ };
113
+ this.callbacks.messages.forEach(callback => callback());
114
+ }
115
+
116
+ protected pushEvent(event: RealtimeServerEvent): void {
117
+ const nextEvents = [...this.state.events, event];
118
+ this.state = {
119
+ ...this.state,
120
+ events:
121
+ nextEvents.length > this.maxEvents
122
+ ? nextEvents.slice(-this.maxEvents)
123
+ : nextEvents,
124
+ };
125
+ this.callbacks.events.forEach(callback => callback());
126
+ }
127
+ }
128
+
129
+ type UseRealtimeReturn = {
130
+ status: RealtimeStatus;
131
+ messages: UIMessage[];
132
+ events: RealtimeServerEvent[];
133
+ isCapturing: boolean;
134
+ isPlaying: boolean;
135
+
136
+ connect: () => Promise<void>;
137
+ disconnect: () => void;
138
+ addToolOutput: (callId: string, result: unknown) => void;
139
+ sendEvent: RealtimeStore['sendEvent'];
140
+ sendTextMessage: (text: string) => void;
141
+ sendAudio: (base64Audio: string) => void;
142
+ commitAudio: () => void;
143
+ clearAudioBuffer: () => void;
144
+ requestResponse: (options?: { modalities?: string[] }) => void;
145
+ cancelResponse: () => void;
146
+ startAudioCapture: (stream: MediaStream) => void;
147
+ stopAudioCapture: () => void;
148
+ stopPlayback: () => void;
149
+ };
150
+
151
+ function useRealtime(options: UseRealtimeOptions): UseRealtimeReturn {
152
+ const callbacksRef = useRef({
153
+ onToolCall: options.onToolCall,
154
+ onEvent: options.onEvent,
155
+ onError: options.onError,
156
+ });
157
+ callbacksRef.current = {
158
+ onToolCall: options.onToolCall,
159
+ onEvent: options.onEvent,
160
+ onError: options.onError,
161
+ };
162
+
163
+ const realtimeRef = useRef<{
164
+ store: RealtimeStore;
165
+ key: RealtimeStoreKey;
166
+ } | null>(null);
167
+
168
+ let realtimeEntry = realtimeRef.current;
169
+
170
+ if (
171
+ realtimeEntry == null ||
172
+ shouldCreateRealtimeStore(realtimeEntry.key, options)
173
+ ) {
174
+ realtimeEntry = {
175
+ store: new RealtimeStore({
176
+ ...options,
177
+ onToolCall: (...args) => callbacksRef.current.onToolCall?.(...args),
178
+ onEvent: (...args) => callbacksRef.current.onEvent?.(...args),
179
+ onError: (...args) => callbacksRef.current.onError?.(...args),
180
+ }),
181
+ key: getRealtimeStoreKey(options),
182
+ };
183
+ realtimeRef.current = realtimeEntry;
184
+ } else {
185
+ realtimeEntry.key = getRealtimeStoreKey(options);
186
+ }
187
+
188
+ const rt = realtimeEntry.store;
189
+
190
+ const status = useSyncExternalStore(
191
+ useCallback(cb => rt.subscribe('status', cb), [rt]),
192
+ () => rt.status,
193
+ () => rt.status,
194
+ );
195
+
196
+ const messages = useSyncExternalStore(
197
+ useCallback(cb => rt.subscribe('messages', cb), [rt]),
198
+ () => rt.messages,
199
+ () => rt.messages,
200
+ );
201
+
202
+ const events = useSyncExternalStore(
203
+ useCallback(cb => rt.subscribe('events', cb), [rt]),
204
+ () => rt.events,
205
+ () => rt.events,
206
+ );
207
+
208
+ const isCapturing = useSyncExternalStore(
209
+ useCallback(cb => rt.subscribe('isCapturing', cb), [rt]),
210
+ () => rt.isCapturing,
211
+ () => rt.isCapturing,
212
+ );
213
+
214
+ const isPlaying = useSyncExternalStore(
215
+ useCallback(cb => rt.subscribe('isPlaying', cb), [rt]),
216
+ () => rt.isPlaying,
217
+ () => rt.isPlaying,
218
+ );
219
+
220
+ useEffect(() => {
221
+ return () => rt.dispose();
222
+ }, [rt]);
223
+
224
+ return {
225
+ status,
226
+ messages,
227
+ events,
228
+ isCapturing,
229
+ isPlaying,
230
+ connect: rt.connect.bind(rt),
231
+ disconnect: rt.disconnect.bind(rt),
232
+ addToolOutput: rt.addToolOutput.bind(rt),
233
+ sendEvent: rt.sendEvent.bind(rt),
234
+ sendTextMessage: rt.sendTextMessage.bind(rt),
235
+ sendAudio: rt.sendAudio.bind(rt),
236
+ commitAudio: rt.commitAudio.bind(rt),
237
+ clearAudioBuffer: rt.clearAudioBuffer.bind(rt),
238
+ requestResponse: rt.requestResponse.bind(rt),
239
+ cancelResponse: rt.cancelResponse.bind(rt),
240
+ startAudioCapture: rt.startAudioCapture.bind(rt),
241
+ stopAudioCapture: rt.stopAudioCapture.bind(rt),
242
+ stopPlayback: rt.stopPlayback.bind(rt),
243
+ };
244
+ }
245
+
246
+ export const experimental_useRealtime = useRealtime;
247
+
248
+ export type {
249
+ RealtimeStatus as Experimental_RealtimeStatus,
250
+ UseRealtimeOptions as Experimental_UseRealtimeOptions,
251
+ UseRealtimeReturn as Experimental_UseRealtimeReturn,
252
+ };
package/dist/index.d.mts DELETED
@@ -1,178 +0,0 @@
1
- import { UIMessage, AbstractChat, ChatInit, CompletionRequestOptions, UseCompletionOptions, DeepPartial } from 'ai';
2
- export { CreateUIMessage, UIMessage, UseCompletionOptions } from 'ai';
3
- import { FlexibleSchema, FetchFunction, Resolvable, InferSchema } from '@ai-sdk/provider-utils';
4
-
5
- declare class Chat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {
6
- #private;
7
- constructor({ messages, ...init }: ChatInit<UI_MESSAGE>);
8
- '~registerMessagesCallback': (onChange: () => void, throttleWaitMs?: number) => (() => void);
9
- '~registerStatusCallback': (onChange: () => void) => (() => void);
10
- '~registerErrorCallback': (onChange: () => void) => (() => void);
11
- }
12
-
13
- type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
14
- /**
15
- * The id of the chat.
16
- */
17
- readonly id: string;
18
- /**
19
- * Update the `messages` state locally. This is useful when you want to
20
- * edit the messages on the client, and then trigger the `reload` method
21
- * manually to regenerate the AI response.
22
- */
23
- setMessages: (messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[])) => void;
24
- error: Error | undefined;
25
- } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError'>;
26
- type UseChatOptions<UI_MESSAGE extends UIMessage> = ({
27
- chat: Chat<UI_MESSAGE>;
28
- } | ChatInit<UI_MESSAGE>) & {
29
- /**
30
- * Custom throttle wait in ms for the chat messages and data updates.
31
- * Default is undefined, which disables throttling.
32
- */
33
- experimental_throttle?: number;
34
- /**
35
- * Whether to resume an ongoing chat generation stream.
36
- */
37
- resume?: boolean;
38
- };
39
- declare function useChat<UI_MESSAGE extends UIMessage = UIMessage>({ experimental_throttle: throttleWaitMs, resume, ...options }?: UseChatOptions<UI_MESSAGE>): UseChatHelpers<UI_MESSAGE>;
40
-
41
- type UseCompletionHelpers = {
42
- /** The current completion result */
43
- completion: string;
44
- /**
45
- * Send a new prompt to the API endpoint and update the completion state.
46
- */
47
- complete: (prompt: string, options?: CompletionRequestOptions) => Promise<string | null | undefined>;
48
- /** The error object of the API request */
49
- error: undefined | Error;
50
- /**
51
- * Abort the current API request but keep the generated tokens.
52
- */
53
- stop: () => void;
54
- /**
55
- * Update the `completion` state locally.
56
- */
57
- setCompletion: (completion: string) => void;
58
- /** The current value of the input */
59
- input: string;
60
- /** setState-powered method to update the input value */
61
- setInput: React.Dispatch<React.SetStateAction<string>>;
62
- /**
63
- * An input/textarea-ready onChange handler to control the value of the input
64
- * @example
65
- * ```jsx
66
- * <input onChange={handleInputChange} value={input} />
67
- * ```
68
- */
69
- handleInputChange: (event: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
70
- /**
71
- * Form submission handler to automatically reset input and append a user message
72
- * @example
73
- * ```jsx
74
- * <form onSubmit={handleSubmit}>
75
- * <input onChange={handleInputChange} value={input} />
76
- * </form>
77
- * ```
78
- */
79
- handleSubmit: (event?: {
80
- preventDefault?: () => void;
81
- }) => void;
82
- /** Whether the API request is in progress */
83
- isLoading: boolean;
84
- };
85
- declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, streamProtocol, fetch, onFinish, onError, experimental_throttle: throttleWaitMs, }?: UseCompletionOptions & {
86
- /**
87
- * Custom throttle wait in ms for the completion and data updates.
88
- * Default is undefined, which disables throttling.
89
- */
90
- experimental_throttle?: number;
91
- }): UseCompletionHelpers;
92
-
93
- type Experimental_UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {
94
- /**
95
- * The API endpoint. It should stream JSON that matches the schema as chunked text.
96
- */
97
- api: string;
98
- /**
99
- * A schema that defines the shape of the complete object.
100
- */
101
- schema: SCHEMA;
102
- /**
103
- * An unique identifier. If not provided, a random one will be
104
- * generated. When provided, the `useObject` hook with the same `id` will
105
- * have shared states across components.
106
- */
107
- id?: string;
108
- /**
109
- * An optional value for the initial object.
110
- */
111
- initialValue?: DeepPartial<RESULT>;
112
- /**
113
- * Custom fetch implementation. You can use it as a middleware to intercept requests,
114
- * or to provide a custom fetch implementation for e.g. testing.
115
- */
116
- fetch?: FetchFunction;
117
- /**
118
- * Callback that is called when the stream has finished.
119
- */
120
- onFinish?: (event: {
121
- /**
122
- * The generated object (typed according to the schema).
123
- * Can be undefined if the final object does not match the schema.
124
- */
125
- object: RESULT | undefined;
126
- /**
127
- * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
128
- */
129
- error: Error | undefined;
130
- }) => Promise<void> | void;
131
- /**
132
- * Callback function to be called when an error is encountered.
133
- */
134
- onError?: (error: Error) => void;
135
- /**
136
- * Additional HTTP headers to be included in the request.
137
- * Can be a static object, a function that returns headers, or an async function
138
- * for dynamic auth tokens.
139
- */
140
- headers?: Resolvable<Record<string, string> | Headers>;
141
- /**
142
- * The credentials mode to be used for the fetch request.
143
- * Possible values are: 'omit', 'same-origin', 'include'.
144
- * Defaults to 'same-origin'.
145
- */
146
- credentials?: RequestCredentials;
147
- };
148
- type Experimental_UseObjectHelpers<RESULT, INPUT> = {
149
- /**
150
- * Calls the API with the provided input as JSON body.
151
- */
152
- submit: (input: INPUT) => void;
153
- /**
154
- * The current value for the generated object. Updated as the API streams JSON chunks.
155
- */
156
- object: DeepPartial<RESULT> | undefined;
157
- /**
158
- * The error object of the API request if any.
159
- */
160
- error: Error | undefined;
161
- /**
162
- * Flag that indicates whether an API request is in progress.
163
- */
164
- isLoading: boolean;
165
- /**
166
- * Abort the current request immediately, keep the current partial object if any.
167
- */
168
- stop: () => void;
169
- /**
170
- * Clear the object state.
171
- */
172
- clear: () => void;
173
- };
174
- declare function useObject<SCHEMA extends FlexibleSchema, RESULT = InferSchema<SCHEMA>, INPUT = any>({ api, id, schema, // required, in the future we will use it for validation
175
- initialValue, fetch, onError, onFinish, headers, credentials, }: Experimental_UseObjectOptions<SCHEMA, RESULT>): Experimental_UseObjectHelpers<RESULT, INPUT>;
176
- declare const experimental_useObject: typeof useObject;
177
-
178
- export { Chat, Experimental_UseObjectHelpers, Experimental_UseObjectOptions, UseChatHelpers, UseChatOptions, UseCompletionHelpers, experimental_useObject, useChat, useCompletion };