@ai-sdk/react 4.0.0-beta.9 → 4.0.0-beta.90
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 +573 -0
- package/dist/index.js +58 -90
- package/dist/index.js.map +1 -1
- package/package.json +10 -13
- package/src/chat.react.ts +3 -3
- package/src/use-object.ts +1 -1
- package/src/vitest-setup.ts +5 -0
- package/dist/index.d.mts +0 -178
- package/dist/index.mjs +0 -506
- package/dist/index.mjs.map +0 -1
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 };
|
package/dist/index.mjs
DELETED
|
@@ -1,506 +0,0 @@
|
|
|
1
|
-
var __accessCheck = (obj, member, msg) => {
|
|
2
|
-
if (!member.has(obj))
|
|
3
|
-
throw TypeError("Cannot " + msg);
|
|
4
|
-
};
|
|
5
|
-
var __privateGet = (obj, member, getter) => {
|
|
6
|
-
__accessCheck(obj, member, "read from private field");
|
|
7
|
-
return getter ? getter.call(obj) : member.get(obj);
|
|
8
|
-
};
|
|
9
|
-
var __privateAdd = (obj, member, value) => {
|
|
10
|
-
if (member.has(obj))
|
|
11
|
-
throw TypeError("Cannot add the same private member more than once");
|
|
12
|
-
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
13
|
-
};
|
|
14
|
-
var __privateSet = (obj, member, value, setter) => {
|
|
15
|
-
__accessCheck(obj, member, "write to private field");
|
|
16
|
-
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
17
|
-
return value;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
// src/use-chat.ts
|
|
21
|
-
import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
|
|
22
|
-
|
|
23
|
-
// src/chat.react.ts
|
|
24
|
-
import { AbstractChat } from "ai";
|
|
25
|
-
|
|
26
|
-
// src/throttle.ts
|
|
27
|
-
import throttleFunction from "throttleit";
|
|
28
|
-
function throttle(fn, waitMs) {
|
|
29
|
-
return waitMs != null ? throttleFunction(fn, waitMs) : fn;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// src/chat.react.ts
|
|
33
|
-
var _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;
|
|
34
|
-
var ReactChatState = class {
|
|
35
|
-
constructor(initialMessages = []) {
|
|
36
|
-
__privateAdd(this, _messages, void 0);
|
|
37
|
-
__privateAdd(this, _status, "ready");
|
|
38
|
-
__privateAdd(this, _error, void 0);
|
|
39
|
-
__privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
|
|
40
|
-
__privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
|
|
41
|
-
__privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
|
|
42
|
-
this.pushMessage = (message) => {
|
|
43
|
-
__privateSet(this, _messages, __privateGet(this, _messages).concat(message));
|
|
44
|
-
__privateGet(this, _callMessagesCallbacks).call(this);
|
|
45
|
-
};
|
|
46
|
-
this.popMessage = () => {
|
|
47
|
-
__privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
|
|
48
|
-
__privateGet(this, _callMessagesCallbacks).call(this);
|
|
49
|
-
};
|
|
50
|
-
this.replaceMessage = (index, message) => {
|
|
51
|
-
__privateSet(this, _messages, [
|
|
52
|
-
...__privateGet(this, _messages).slice(0, index),
|
|
53
|
-
// We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
|
|
54
|
-
this.snapshot(message),
|
|
55
|
-
...__privateGet(this, _messages).slice(index + 1)
|
|
56
|
-
]);
|
|
57
|
-
__privateGet(this, _callMessagesCallbacks).call(this);
|
|
58
|
-
};
|
|
59
|
-
this.snapshot = (value) => structuredClone(value);
|
|
60
|
-
this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
|
|
61
|
-
const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
|
|
62
|
-
__privateGet(this, _messagesCallbacks).add(callback);
|
|
63
|
-
return () => {
|
|
64
|
-
__privateGet(this, _messagesCallbacks).delete(callback);
|
|
65
|
-
};
|
|
66
|
-
};
|
|
67
|
-
this["~registerStatusCallback"] = (onChange) => {
|
|
68
|
-
__privateGet(this, _statusCallbacks).add(onChange);
|
|
69
|
-
return () => {
|
|
70
|
-
__privateGet(this, _statusCallbacks).delete(onChange);
|
|
71
|
-
};
|
|
72
|
-
};
|
|
73
|
-
this["~registerErrorCallback"] = (onChange) => {
|
|
74
|
-
__privateGet(this, _errorCallbacks).add(onChange);
|
|
75
|
-
return () => {
|
|
76
|
-
__privateGet(this, _errorCallbacks).delete(onChange);
|
|
77
|
-
};
|
|
78
|
-
};
|
|
79
|
-
__privateAdd(this, _callMessagesCallbacks, () => {
|
|
80
|
-
__privateGet(this, _messagesCallbacks).forEach((callback) => callback());
|
|
81
|
-
});
|
|
82
|
-
__privateAdd(this, _callStatusCallbacks, () => {
|
|
83
|
-
__privateGet(this, _statusCallbacks).forEach((callback) => callback());
|
|
84
|
-
});
|
|
85
|
-
__privateAdd(this, _callErrorCallbacks, () => {
|
|
86
|
-
__privateGet(this, _errorCallbacks).forEach((callback) => callback());
|
|
87
|
-
});
|
|
88
|
-
__privateSet(this, _messages, initialMessages);
|
|
89
|
-
}
|
|
90
|
-
get status() {
|
|
91
|
-
return __privateGet(this, _status);
|
|
92
|
-
}
|
|
93
|
-
set status(newStatus) {
|
|
94
|
-
__privateSet(this, _status, newStatus);
|
|
95
|
-
__privateGet(this, _callStatusCallbacks).call(this);
|
|
96
|
-
}
|
|
97
|
-
get error() {
|
|
98
|
-
return __privateGet(this, _error);
|
|
99
|
-
}
|
|
100
|
-
set error(newError) {
|
|
101
|
-
__privateSet(this, _error, newError);
|
|
102
|
-
__privateGet(this, _callErrorCallbacks).call(this);
|
|
103
|
-
}
|
|
104
|
-
get messages() {
|
|
105
|
-
return __privateGet(this, _messages);
|
|
106
|
-
}
|
|
107
|
-
set messages(newMessages) {
|
|
108
|
-
__privateSet(this, _messages, [...newMessages]);
|
|
109
|
-
__privateGet(this, _callMessagesCallbacks).call(this);
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
_messages = new WeakMap();
|
|
113
|
-
_status = new WeakMap();
|
|
114
|
-
_error = new WeakMap();
|
|
115
|
-
_messagesCallbacks = new WeakMap();
|
|
116
|
-
_statusCallbacks = new WeakMap();
|
|
117
|
-
_errorCallbacks = new WeakMap();
|
|
118
|
-
_callMessagesCallbacks = new WeakMap();
|
|
119
|
-
_callStatusCallbacks = new WeakMap();
|
|
120
|
-
_callErrorCallbacks = new WeakMap();
|
|
121
|
-
var _state;
|
|
122
|
-
var Chat = class extends AbstractChat {
|
|
123
|
-
constructor({ messages, ...init }) {
|
|
124
|
-
const state = new ReactChatState(messages);
|
|
125
|
-
super({ ...init, state });
|
|
126
|
-
__privateAdd(this, _state, void 0);
|
|
127
|
-
this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
|
|
128
|
-
this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
|
|
129
|
-
this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
|
|
130
|
-
__privateSet(this, _state, state);
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
_state = new WeakMap();
|
|
134
|
-
|
|
135
|
-
// src/use-chat.ts
|
|
136
|
-
function useChat({
|
|
137
|
-
experimental_throttle: throttleWaitMs,
|
|
138
|
-
resume = false,
|
|
139
|
-
...options
|
|
140
|
-
} = {}) {
|
|
141
|
-
const callbacksRef = useRef(
|
|
142
|
-
!("chat" in options) ? {
|
|
143
|
-
onToolCall: options.onToolCall,
|
|
144
|
-
onData: options.onData,
|
|
145
|
-
onFinish: options.onFinish,
|
|
146
|
-
onError: options.onError,
|
|
147
|
-
sendAutomaticallyWhen: options.sendAutomaticallyWhen
|
|
148
|
-
} : {}
|
|
149
|
-
);
|
|
150
|
-
if (!("chat" in options)) {
|
|
151
|
-
callbacksRef.current = {
|
|
152
|
-
onToolCall: options.onToolCall,
|
|
153
|
-
onData: options.onData,
|
|
154
|
-
onFinish: options.onFinish,
|
|
155
|
-
onError: options.onError,
|
|
156
|
-
sendAutomaticallyWhen: options.sendAutomaticallyWhen
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
const optionsWithCallbacks = {
|
|
160
|
-
...options,
|
|
161
|
-
onToolCall: (arg) => {
|
|
162
|
-
var _a, _b;
|
|
163
|
-
return (_b = (_a = callbacksRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
|
|
164
|
-
},
|
|
165
|
-
onData: (arg) => {
|
|
166
|
-
var _a, _b;
|
|
167
|
-
return (_b = (_a = callbacksRef.current).onData) == null ? void 0 : _b.call(_a, arg);
|
|
168
|
-
},
|
|
169
|
-
onFinish: (arg) => {
|
|
170
|
-
var _a, _b;
|
|
171
|
-
return (_b = (_a = callbacksRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
|
|
172
|
-
},
|
|
173
|
-
onError: (arg) => {
|
|
174
|
-
var _a, _b;
|
|
175
|
-
return (_b = (_a = callbacksRef.current).onError) == null ? void 0 : _b.call(_a, arg);
|
|
176
|
-
},
|
|
177
|
-
sendAutomaticallyWhen: (arg) => {
|
|
178
|
-
var _a, _b, _c;
|
|
179
|
-
return (_c = (_b = (_a = callbacksRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
const chatRef = useRef(
|
|
183
|
-
"chat" in options ? options.chat : new Chat(optionsWithCallbacks)
|
|
184
|
-
);
|
|
185
|
-
const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && chatRef.current.id !== options.id;
|
|
186
|
-
if (shouldRecreateChat) {
|
|
187
|
-
chatRef.current = "chat" in options ? options.chat : new Chat(optionsWithCallbacks);
|
|
188
|
-
}
|
|
189
|
-
const subscribeToMessages = useCallback(
|
|
190
|
-
(update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
|
|
191
|
-
// `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
|
|
192
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
193
|
-
[throttleWaitMs, chatRef.current.id]
|
|
194
|
-
);
|
|
195
|
-
const messages = useSyncExternalStore(
|
|
196
|
-
subscribeToMessages,
|
|
197
|
-
() => chatRef.current.messages,
|
|
198
|
-
() => chatRef.current.messages
|
|
199
|
-
);
|
|
200
|
-
const status = useSyncExternalStore(
|
|
201
|
-
chatRef.current["~registerStatusCallback"],
|
|
202
|
-
() => chatRef.current.status,
|
|
203
|
-
() => chatRef.current.status
|
|
204
|
-
);
|
|
205
|
-
const error = useSyncExternalStore(
|
|
206
|
-
chatRef.current["~registerErrorCallback"],
|
|
207
|
-
() => chatRef.current.error,
|
|
208
|
-
() => chatRef.current.error
|
|
209
|
-
);
|
|
210
|
-
const setMessages = useCallback(
|
|
211
|
-
(messagesParam) => {
|
|
212
|
-
if (typeof messagesParam === "function") {
|
|
213
|
-
messagesParam = messagesParam(chatRef.current.messages);
|
|
214
|
-
}
|
|
215
|
-
chatRef.current.messages = messagesParam;
|
|
216
|
-
},
|
|
217
|
-
[chatRef]
|
|
218
|
-
);
|
|
219
|
-
useEffect(() => {
|
|
220
|
-
if (resume) {
|
|
221
|
-
chatRef.current.resumeStream();
|
|
222
|
-
}
|
|
223
|
-
}, [resume, chatRef]);
|
|
224
|
-
return {
|
|
225
|
-
id: chatRef.current.id,
|
|
226
|
-
messages,
|
|
227
|
-
setMessages,
|
|
228
|
-
sendMessage: chatRef.current.sendMessage,
|
|
229
|
-
regenerate: chatRef.current.regenerate,
|
|
230
|
-
clearError: chatRef.current.clearError,
|
|
231
|
-
stop: chatRef.current.stop,
|
|
232
|
-
error,
|
|
233
|
-
resumeStream: chatRef.current.resumeStream,
|
|
234
|
-
status,
|
|
235
|
-
/**
|
|
236
|
-
* @deprecated Use `addToolOutput` instead.
|
|
237
|
-
*/
|
|
238
|
-
addToolResult: chatRef.current.addToolOutput,
|
|
239
|
-
addToolOutput: chatRef.current.addToolOutput,
|
|
240
|
-
addToolApprovalResponse: chatRef.current.addToolApprovalResponse
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// src/use-completion.ts
|
|
245
|
-
import {
|
|
246
|
-
callCompletionApi
|
|
247
|
-
} from "ai";
|
|
248
|
-
import { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from "react";
|
|
249
|
-
import useSWR from "swr";
|
|
250
|
-
function useCompletion({
|
|
251
|
-
api = "/api/completion",
|
|
252
|
-
id,
|
|
253
|
-
initialCompletion = "",
|
|
254
|
-
initialInput = "",
|
|
255
|
-
credentials,
|
|
256
|
-
headers,
|
|
257
|
-
body,
|
|
258
|
-
streamProtocol = "data",
|
|
259
|
-
fetch: fetch2,
|
|
260
|
-
onFinish,
|
|
261
|
-
onError,
|
|
262
|
-
experimental_throttle: throttleWaitMs
|
|
263
|
-
} = {}) {
|
|
264
|
-
const hookId = useId();
|
|
265
|
-
const completionId = id || hookId;
|
|
266
|
-
const { data, mutate } = useSWR([api, completionId], null, {
|
|
267
|
-
fallbackData: initialCompletion
|
|
268
|
-
});
|
|
269
|
-
const { data: isLoading = false, mutate: mutateLoading } = useSWR(
|
|
270
|
-
[completionId, "loading"],
|
|
271
|
-
null
|
|
272
|
-
);
|
|
273
|
-
const [error, setError] = useState(void 0);
|
|
274
|
-
const completion = data;
|
|
275
|
-
const [abortController, setAbortController] = useState(null);
|
|
276
|
-
const extraMetadataRef = useRef2({
|
|
277
|
-
credentials,
|
|
278
|
-
headers,
|
|
279
|
-
body
|
|
280
|
-
});
|
|
281
|
-
useEffect2(() => {
|
|
282
|
-
extraMetadataRef.current = {
|
|
283
|
-
credentials,
|
|
284
|
-
headers,
|
|
285
|
-
body
|
|
286
|
-
};
|
|
287
|
-
}, [credentials, headers, body]);
|
|
288
|
-
const triggerRequest = useCallback2(
|
|
289
|
-
async (prompt, options) => callCompletionApi({
|
|
290
|
-
api,
|
|
291
|
-
prompt,
|
|
292
|
-
credentials: extraMetadataRef.current.credentials,
|
|
293
|
-
headers: { ...extraMetadataRef.current.headers, ...options == null ? void 0 : options.headers },
|
|
294
|
-
body: {
|
|
295
|
-
...extraMetadataRef.current.body,
|
|
296
|
-
...options == null ? void 0 : options.body
|
|
297
|
-
},
|
|
298
|
-
streamProtocol,
|
|
299
|
-
fetch: fetch2,
|
|
300
|
-
// throttle streamed ui updates:
|
|
301
|
-
setCompletion: throttle(
|
|
302
|
-
(completion2) => mutate(completion2, false),
|
|
303
|
-
throttleWaitMs
|
|
304
|
-
),
|
|
305
|
-
setLoading: mutateLoading,
|
|
306
|
-
setError,
|
|
307
|
-
setAbortController,
|
|
308
|
-
onFinish,
|
|
309
|
-
onError
|
|
310
|
-
}),
|
|
311
|
-
[
|
|
312
|
-
mutate,
|
|
313
|
-
mutateLoading,
|
|
314
|
-
api,
|
|
315
|
-
extraMetadataRef,
|
|
316
|
-
setAbortController,
|
|
317
|
-
onFinish,
|
|
318
|
-
onError,
|
|
319
|
-
setError,
|
|
320
|
-
streamProtocol,
|
|
321
|
-
fetch2,
|
|
322
|
-
throttleWaitMs
|
|
323
|
-
]
|
|
324
|
-
);
|
|
325
|
-
const stop = useCallback2(() => {
|
|
326
|
-
if (abortController) {
|
|
327
|
-
abortController.abort();
|
|
328
|
-
setAbortController(null);
|
|
329
|
-
}
|
|
330
|
-
}, [abortController]);
|
|
331
|
-
const setCompletion = useCallback2(
|
|
332
|
-
(completion2) => {
|
|
333
|
-
mutate(completion2, false);
|
|
334
|
-
},
|
|
335
|
-
[mutate]
|
|
336
|
-
);
|
|
337
|
-
const complete = useCallback2(
|
|
338
|
-
async (prompt, options) => {
|
|
339
|
-
return triggerRequest(prompt, options);
|
|
340
|
-
},
|
|
341
|
-
[triggerRequest]
|
|
342
|
-
);
|
|
343
|
-
const [input, setInput] = useState(initialInput);
|
|
344
|
-
const handleSubmit = useCallback2(
|
|
345
|
-
(event) => {
|
|
346
|
-
var _a;
|
|
347
|
-
(_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
|
|
348
|
-
return input ? complete(input) : void 0;
|
|
349
|
-
},
|
|
350
|
-
[input, complete]
|
|
351
|
-
);
|
|
352
|
-
const handleInputChange = useCallback2(
|
|
353
|
-
(e) => {
|
|
354
|
-
setInput(e.target.value);
|
|
355
|
-
},
|
|
356
|
-
[setInput]
|
|
357
|
-
);
|
|
358
|
-
return {
|
|
359
|
-
completion,
|
|
360
|
-
complete,
|
|
361
|
-
error,
|
|
362
|
-
setCompletion,
|
|
363
|
-
stop,
|
|
364
|
-
input,
|
|
365
|
-
setInput,
|
|
366
|
-
handleInputChange,
|
|
367
|
-
handleSubmit,
|
|
368
|
-
isLoading
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// src/use-object.ts
|
|
373
|
-
import {
|
|
374
|
-
isAbortError,
|
|
375
|
-
resolve,
|
|
376
|
-
normalizeHeaders,
|
|
377
|
-
safeValidateTypes
|
|
378
|
-
} from "@ai-sdk/provider-utils";
|
|
379
|
-
import { asSchema, isDeepEqualData, parsePartialJson } from "ai";
|
|
380
|
-
import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
|
|
381
|
-
import useSWR2 from "swr";
|
|
382
|
-
var getOriginalFetch = () => fetch;
|
|
383
|
-
function useObject({
|
|
384
|
-
api,
|
|
385
|
-
id,
|
|
386
|
-
schema,
|
|
387
|
-
// required, in the future we will use it for validation
|
|
388
|
-
initialValue,
|
|
389
|
-
fetch: fetch2,
|
|
390
|
-
onError,
|
|
391
|
-
onFinish,
|
|
392
|
-
headers,
|
|
393
|
-
credentials
|
|
394
|
-
}) {
|
|
395
|
-
const hookId = useId2();
|
|
396
|
-
const completionId = id != null ? id : hookId;
|
|
397
|
-
const { data, mutate } = useSWR2(
|
|
398
|
-
[api, completionId],
|
|
399
|
-
null,
|
|
400
|
-
{ fallbackData: initialValue }
|
|
401
|
-
);
|
|
402
|
-
const [error, setError] = useState2(void 0);
|
|
403
|
-
const [isLoading, setIsLoading] = useState2(false);
|
|
404
|
-
const abortControllerRef = useRef3(null);
|
|
405
|
-
const stop = useCallback3(() => {
|
|
406
|
-
var _a;
|
|
407
|
-
try {
|
|
408
|
-
(_a = abortControllerRef.current) == null ? void 0 : _a.abort();
|
|
409
|
-
} catch (ignored) {
|
|
410
|
-
} finally {
|
|
411
|
-
setIsLoading(false);
|
|
412
|
-
abortControllerRef.current = null;
|
|
413
|
-
}
|
|
414
|
-
}, []);
|
|
415
|
-
const submit = async (input) => {
|
|
416
|
-
var _a;
|
|
417
|
-
try {
|
|
418
|
-
clearObject();
|
|
419
|
-
setIsLoading(true);
|
|
420
|
-
const abortController = new AbortController();
|
|
421
|
-
abortControllerRef.current = abortController;
|
|
422
|
-
const resolvedHeaders = await resolve(headers);
|
|
423
|
-
const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
|
|
424
|
-
const response = await actualFetch(api, {
|
|
425
|
-
method: "POST",
|
|
426
|
-
headers: {
|
|
427
|
-
"Content-Type": "application/json",
|
|
428
|
-
...normalizeHeaders(resolvedHeaders)
|
|
429
|
-
},
|
|
430
|
-
credentials,
|
|
431
|
-
signal: abortController.signal,
|
|
432
|
-
body: JSON.stringify(input)
|
|
433
|
-
});
|
|
434
|
-
if (!response.ok) {
|
|
435
|
-
throw new Error(
|
|
436
|
-
(_a = await response.text()) != null ? _a : "Failed to fetch the response."
|
|
437
|
-
);
|
|
438
|
-
}
|
|
439
|
-
if (response.body == null) {
|
|
440
|
-
throw new Error("The response body is empty.");
|
|
441
|
-
}
|
|
442
|
-
let accumulatedText = "";
|
|
443
|
-
let latestObject = void 0;
|
|
444
|
-
await response.body.pipeThrough(new TextDecoderStream()).pipeTo(
|
|
445
|
-
new WritableStream({
|
|
446
|
-
async write(chunk) {
|
|
447
|
-
accumulatedText += chunk;
|
|
448
|
-
const { value } = await parsePartialJson(accumulatedText);
|
|
449
|
-
const currentObject = value;
|
|
450
|
-
if (!isDeepEqualData(latestObject, currentObject)) {
|
|
451
|
-
latestObject = currentObject;
|
|
452
|
-
mutate(currentObject);
|
|
453
|
-
}
|
|
454
|
-
},
|
|
455
|
-
async close() {
|
|
456
|
-
setIsLoading(false);
|
|
457
|
-
abortControllerRef.current = null;
|
|
458
|
-
if (onFinish != null) {
|
|
459
|
-
const validationResult = await safeValidateTypes({
|
|
460
|
-
value: latestObject,
|
|
461
|
-
schema: asSchema(schema)
|
|
462
|
-
});
|
|
463
|
-
onFinish(
|
|
464
|
-
validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }
|
|
465
|
-
);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
})
|
|
469
|
-
);
|
|
470
|
-
} catch (error2) {
|
|
471
|
-
if (isAbortError(error2)) {
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
if (onError && error2 instanceof Error) {
|
|
475
|
-
onError(error2);
|
|
476
|
-
}
|
|
477
|
-
setIsLoading(false);
|
|
478
|
-
setError(error2 instanceof Error ? error2 : new Error(String(error2)));
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
const clear = () => {
|
|
482
|
-
stop();
|
|
483
|
-
clearObject();
|
|
484
|
-
};
|
|
485
|
-
const clearObject = () => {
|
|
486
|
-
setError(void 0);
|
|
487
|
-
setIsLoading(false);
|
|
488
|
-
mutate(void 0);
|
|
489
|
-
};
|
|
490
|
-
return {
|
|
491
|
-
submit,
|
|
492
|
-
object: data,
|
|
493
|
-
error,
|
|
494
|
-
isLoading,
|
|
495
|
-
stop,
|
|
496
|
-
clear
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
var experimental_useObject = useObject;
|
|
500
|
-
export {
|
|
501
|
-
Chat,
|
|
502
|
-
experimental_useObject,
|
|
503
|
-
useChat,
|
|
504
|
-
useCompletion
|
|
505
|
-
};
|
|
506
|
-
//# sourceMappingURL=index.mjs.map
|