ai 2.1.0 → 2.1.3

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.
Files changed (71) hide show
  1. package/README.md +89 -0
  2. package/dist/index.d.ts +48 -8
  3. package/dist/index.mjs +234 -26
  4. package/package.json +4 -4
  5. package/react/dist/index.d.ts +206 -3
  6. package/react/dist/index.js +2 -1
  7. package/react/dist/index.mjs +385 -7
  8. package/svelte/dist/index.d.ts +194 -4
  9. package/svelte/dist/index.js +2 -1
  10. package/svelte/dist/index.mjs +780 -7
  11. package/vue/dist/index.d.ts +194 -4
  12. package/vue/dist/index.mjs +345 -7
  13. package/dist/ai-stream.d.ts +0 -18
  14. package/dist/ai-stream.js +0 -132
  15. package/dist/ai-stream.mjs +0 -15
  16. package/dist/anthropic-stream.d.ts +0 -5
  17. package/dist/anthropic-stream.js +0 -133
  18. package/dist/anthropic-stream.mjs +0 -10
  19. package/dist/chunk-2JQWCLY2.mjs +0 -70
  20. package/dist/chunk-7KLTYB74.mjs +0 -70
  21. package/dist/chunk-BJMBMGA3.mjs +0 -34
  22. package/dist/chunk-KKQRUR3E.mjs +0 -51
  23. package/dist/chunk-RBP6ONSV.mjs +0 -45
  24. package/dist/chunk-TWW2ODJW.mjs +0 -32
  25. package/dist/chunk-U2OQ6HW6.mjs +0 -41
  26. package/dist/chunk-UJV6VDVU.mjs +0 -97
  27. package/dist/huggingface-stream.d.ts +0 -5
  28. package/dist/huggingface-stream.js +0 -121
  29. package/dist/huggingface-stream.mjs +0 -10
  30. package/dist/index.test.d.ts +0 -2
  31. package/dist/index.test.js +0 -568
  32. package/dist/index.test.mjs +0 -286
  33. package/dist/langchain-stream.d.ts +0 -12
  34. package/dist/langchain-stream.js +0 -102
  35. package/dist/langchain-stream.mjs +0 -10
  36. package/dist/openai-stream.d.ts +0 -5
  37. package/dist/openai-stream.js +0 -144
  38. package/dist/openai-stream.mjs +0 -10
  39. package/dist/streaming-text-response.d.ts +0 -17
  40. package/dist/streaming-text-response.js +0 -75
  41. package/dist/streaming-text-response.mjs +0 -11
  42. package/react/dist/chunk-5PP6W52J.mjs +0 -202
  43. package/react/dist/chunk-6EH3SWMP.mjs +0 -55
  44. package/react/dist/chunk-PW6HSU2N.mjs +0 -154
  45. package/react/dist/types-f862f74a.d.ts +0 -123
  46. package/react/dist/use-chat.d.ts +0 -42
  47. package/react/dist/use-chat.js +0 -276
  48. package/react/dist/use-chat.mjs +0 -8
  49. package/react/dist/use-completion.d.ts +0 -47
  50. package/react/dist/use-completion.js +0 -229
  51. package/react/dist/use-completion.mjs +0 -8
  52. package/svelte/dist/chunk-6USBQIV6.mjs +0 -177
  53. package/svelte/dist/chunk-BQ64GHZ3.mjs +0 -136
  54. package/svelte/dist/chunk-CENOSGDG.mjs +0 -493
  55. package/svelte/dist/types-f862f74a.d.ts +0 -123
  56. package/svelte/dist/use-chat.d.ts +0 -39
  57. package/svelte/dist/use-chat.js +0 -680
  58. package/svelte/dist/use-chat.mjs +0 -7
  59. package/svelte/dist/use-completion.d.ts +0 -38
  60. package/svelte/dist/use-completion.js +0 -640
  61. package/svelte/dist/use-completion.mjs +0 -7
  62. package/vue/dist/chunk-FT26CHLO.mjs +0 -137
  63. package/vue/dist/chunk-OYI6GFBM.mjs +0 -178
  64. package/vue/dist/chunk-WXH4YPZV.mjs +0 -54
  65. package/vue/dist/types-f862f74a.d.ts +0 -123
  66. package/vue/dist/use-chat.d.ts +0 -39
  67. package/vue/dist/use-chat.js +0 -252
  68. package/vue/dist/use-chat.mjs +0 -7
  69. package/vue/dist/use-completion.d.ts +0 -38
  70. package/vue/dist/use-completion.js +0 -212
  71. package/vue/dist/use-completion.mjs +0 -7
@@ -1,11 +1,389 @@
1
1
  'use client'
2
- import {
3
- useChat
4
- } from "./chunk-5PP6W52J.mjs";
5
- import {
6
- useCompletion
7
- } from "./chunk-PW6HSU2N.mjs";
8
- import "./chunk-6EH3SWMP.mjs";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __spreadValues = (a, b) => {
8
+ for (var prop in b || (b = {}))
9
+ if (__hasOwnProp.call(b, prop))
10
+ __defNormalProp(a, prop, b[prop]);
11
+ if (__getOwnPropSymbols)
12
+ for (var prop of __getOwnPropSymbols(b)) {
13
+ if (__propIsEnum.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ }
16
+ return a;
17
+ };
18
+ var __async = (__this, __arguments, generator) => {
19
+ return new Promise((resolve, reject) => {
20
+ var fulfilled = (value) => {
21
+ try {
22
+ step(generator.next(value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ };
27
+ var rejected = (value) => {
28
+ try {
29
+ step(generator.throw(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
35
+ step((generator = generator.apply(__this, __arguments)).next());
36
+ });
37
+ };
38
+
39
+ // react/use-chat.ts
40
+ import { useCallback, useId, useRef, useEffect, useState } from "react";
41
+ import useSWRMutation from "swr/mutation";
42
+ import useSWR from "swr";
43
+
44
+ // shared/utils.ts
45
+ import { customAlphabet } from "nanoid";
46
+ var nanoid = customAlphabet(
47
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
48
+ 7
49
+ );
50
+ var decoder = new TextDecoder();
51
+ function decodeAIStreamChunk(chunk) {
52
+ return decoder.decode(chunk);
53
+ }
54
+
55
+ // react/use-chat.ts
56
+ function useChat({
57
+ api = "/api/chat",
58
+ id,
59
+ initialMessages = [],
60
+ initialInput = "",
61
+ sendExtraMessageFields,
62
+ onResponse,
63
+ onFinish,
64
+ onError,
65
+ headers,
66
+ body
67
+ } = {}) {
68
+ const hookId = useId();
69
+ const chatId = id || hookId;
70
+ const { data, mutate } = useSWR([api, chatId], null, {
71
+ fallbackData: initialMessages
72
+ });
73
+ const messages = data;
74
+ const messagesRef = useRef(messages);
75
+ useEffect(() => {
76
+ messagesRef.current = messages;
77
+ }, [messages]);
78
+ const abortControllerRef = useRef(null);
79
+ const extraMetadataRef = useRef({
80
+ headers,
81
+ body
82
+ });
83
+ useEffect(() => {
84
+ extraMetadataRef.current = {
85
+ headers,
86
+ body
87
+ };
88
+ }, [headers, body]);
89
+ const { error, trigger, isMutating } = useSWRMutation(
90
+ [api, chatId],
91
+ (_0, _1) => __async(this, [_0, _1], function* (_, { arg: messagesSnapshot }) {
92
+ try {
93
+ const abortController = new AbortController();
94
+ abortControllerRef.current = abortController;
95
+ const previousMessages = messagesRef.current;
96
+ mutate(messagesSnapshot, false);
97
+ const res = yield fetch(api, {
98
+ method: "POST",
99
+ body: JSON.stringify(__spreadValues({
100
+ messages: sendExtraMessageFields ? messagesSnapshot : messagesSnapshot.map(({ role, content }) => ({
101
+ role,
102
+ content
103
+ }))
104
+ }, extraMetadataRef.current.body)),
105
+ headers: extraMetadataRef.current.headers || {},
106
+ signal: abortController.signal
107
+ }).catch((err) => {
108
+ mutate(previousMessages, false);
109
+ throw err;
110
+ });
111
+ if (onResponse) {
112
+ try {
113
+ yield onResponse(res);
114
+ } catch (err) {
115
+ throw err;
116
+ }
117
+ }
118
+ if (!res.ok) {
119
+ mutate(previousMessages, false);
120
+ throw new Error(
121
+ (yield res.text()) || "Failed to fetch the chat response."
122
+ );
123
+ }
124
+ if (!res.body) {
125
+ throw new Error("The response body is empty.");
126
+ }
127
+ let result = "";
128
+ const createdAt = /* @__PURE__ */ new Date();
129
+ const replyId = nanoid();
130
+ const reader = res.body.getReader();
131
+ while (true) {
132
+ const { done, value } = yield reader.read();
133
+ if (done) {
134
+ break;
135
+ }
136
+ result += decodeAIStreamChunk(value);
137
+ mutate(
138
+ [
139
+ ...messagesSnapshot,
140
+ {
141
+ id: replyId,
142
+ createdAt,
143
+ content: result,
144
+ role: "assistant"
145
+ }
146
+ ],
147
+ false
148
+ );
149
+ if (abortControllerRef.current === null) {
150
+ reader.cancel();
151
+ break;
152
+ }
153
+ }
154
+ if (onFinish) {
155
+ onFinish({
156
+ id: replyId,
157
+ createdAt,
158
+ content: result,
159
+ role: "assistant"
160
+ });
161
+ }
162
+ abortControllerRef.current = null;
163
+ return result;
164
+ } catch (err) {
165
+ if (err.name === "AbortError") {
166
+ abortControllerRef.current = null;
167
+ return null;
168
+ }
169
+ if (onError && err instanceof Error) {
170
+ onError(err);
171
+ }
172
+ throw err;
173
+ }
174
+ }),
175
+ {
176
+ populateCache: false,
177
+ revalidate: false
178
+ }
179
+ );
180
+ const append = useCallback(
181
+ (message) => __async(this, null, function* () {
182
+ if (!message.id) {
183
+ message.id = nanoid();
184
+ }
185
+ return trigger(messagesRef.current.concat(message));
186
+ }),
187
+ [trigger]
188
+ );
189
+ const reload = useCallback(() => __async(this, null, function* () {
190
+ if (messagesRef.current.length === 0)
191
+ return null;
192
+ const lastMessage = messagesRef.current[messagesRef.current.length - 1];
193
+ if (lastMessage.role === "assistant") {
194
+ return trigger(messagesRef.current.slice(0, -1));
195
+ }
196
+ return trigger(messagesRef.current);
197
+ }), [trigger]);
198
+ const stop = useCallback(() => {
199
+ if (abortControllerRef.current) {
200
+ abortControllerRef.current.abort();
201
+ abortControllerRef.current = null;
202
+ }
203
+ }, []);
204
+ const setMessages = useCallback(
205
+ (messages2) => {
206
+ mutate(messages2, false);
207
+ messagesRef.current = messages2;
208
+ },
209
+ [mutate]
210
+ );
211
+ const [input, setInput] = useState(initialInput);
212
+ const handleSubmit = useCallback(
213
+ (e) => {
214
+ e.preventDefault();
215
+ if (!input)
216
+ return;
217
+ append({
218
+ content: input,
219
+ role: "user",
220
+ createdAt: /* @__PURE__ */ new Date()
221
+ });
222
+ setInput("");
223
+ },
224
+ [input, append]
225
+ );
226
+ const handleInputChange = (e) => {
227
+ setInput(e.target.value);
228
+ };
229
+ return {
230
+ messages,
231
+ error,
232
+ append,
233
+ reload,
234
+ stop,
235
+ setMessages,
236
+ input,
237
+ setInput,
238
+ handleInputChange,
239
+ handleSubmit,
240
+ isLoading: isMutating
241
+ };
242
+ }
243
+
244
+ // react/use-completion.ts
245
+ import { useCallback as useCallback2, useEffect as useEffect2, useId as useId2, useRef as useRef2, useState as useState2 } from "react";
246
+ import useSWRMutation2 from "swr/mutation";
247
+ import useSWR2 from "swr";
248
+ function useCompletion({
249
+ api = "/api/completion",
250
+ id,
251
+ initialCompletion = "",
252
+ initialInput = "",
253
+ headers,
254
+ body,
255
+ onResponse,
256
+ onFinish,
257
+ onError
258
+ } = {}) {
259
+ const hookId = useId2();
260
+ const completionId = id || hookId;
261
+ const { data, mutate } = useSWR2([api, completionId], null, {
262
+ fallbackData: initialCompletion
263
+ });
264
+ const completion = data;
265
+ const [abortController, setAbortController] = useState2(null);
266
+ const extraMetadataRef = useRef2({
267
+ headers,
268
+ body
269
+ });
270
+ useEffect2(() => {
271
+ extraMetadataRef.current = {
272
+ headers,
273
+ body
274
+ };
275
+ }, [headers, body]);
276
+ const { error, trigger, isMutating } = useSWRMutation2(
277
+ [api, completionId],
278
+ (_0, _1) => __async(this, [_0, _1], function* (_, { arg: prompt }) {
279
+ try {
280
+ const abortController2 = new AbortController();
281
+ setAbortController(abortController2);
282
+ mutate("", false);
283
+ const res = yield fetch(api, {
284
+ method: "POST",
285
+ body: JSON.stringify(__spreadValues({
286
+ prompt
287
+ }, extraMetadataRef.current.body)),
288
+ headers: extraMetadataRef.current.headers || {},
289
+ signal: abortController2.signal
290
+ }).catch((err) => {
291
+ throw err;
292
+ });
293
+ if (onResponse) {
294
+ try {
295
+ yield onResponse(res);
296
+ } catch (err) {
297
+ throw err;
298
+ }
299
+ }
300
+ if (!res.ok) {
301
+ throw new Error(
302
+ (yield res.text()) || "Failed to fetch the chat response."
303
+ );
304
+ }
305
+ if (!res.body) {
306
+ throw new Error("The response body is empty.");
307
+ }
308
+ let result = "";
309
+ const reader = res.body.getReader();
310
+ while (true) {
311
+ const { done, value } = yield reader.read();
312
+ if (done) {
313
+ break;
314
+ }
315
+ result += decodeAIStreamChunk(value);
316
+ mutate(result, false);
317
+ if (abortController2 === null) {
318
+ reader.cancel();
319
+ break;
320
+ }
321
+ }
322
+ if (onFinish) {
323
+ onFinish(prompt, result);
324
+ }
325
+ setAbortController(null);
326
+ return result;
327
+ } catch (err) {
328
+ if (err.name === "AbortError") {
329
+ setAbortController(null);
330
+ return null;
331
+ }
332
+ if (onError && err instanceof Error) {
333
+ onError(err);
334
+ }
335
+ throw err;
336
+ }
337
+ }),
338
+ {
339
+ populateCache: false,
340
+ revalidate: false
341
+ }
342
+ );
343
+ const stop = useCallback2(() => {
344
+ if (abortController) {
345
+ abortController.abort();
346
+ setAbortController(null);
347
+ }
348
+ }, [abortController]);
349
+ const setCompletion = useCallback2(
350
+ (completion2) => {
351
+ mutate(completion2, false);
352
+ },
353
+ [mutate]
354
+ );
355
+ const [input, setInput] = useState2(initialInput);
356
+ const handleSubmit = useCallback2(
357
+ (e) => {
358
+ e.preventDefault();
359
+ if (!input)
360
+ return;
361
+ return trigger(input);
362
+ },
363
+ [input, trigger]
364
+ );
365
+ const handleInputChange = (e) => {
366
+ setInput(e.target.value);
367
+ };
368
+ const complete = useCallback2(
369
+ (prompt) => __async(this, null, function* () {
370
+ return trigger(prompt);
371
+ }),
372
+ [trigger]
373
+ );
374
+ return {
375
+ completion,
376
+ complete,
377
+ error,
378
+ setCompletion,
379
+ stop,
380
+ input,
381
+ setInput,
382
+ handleInputChange,
383
+ handleSubmit,
384
+ isLoading: isMutating
385
+ };
386
+ }
9
387
  export {
10
388
  useChat,
11
389
  useCompletion
@@ -1,4 +1,194 @@
1
- export { UseChatHelpers, useChat } from './use-chat.js';
2
- export { UseCompletionHelpers, useCompletion } from './use-completion.js';
3
- export { C as CreateMessage, M as Message, U as UseChatOptions } from './types-f862f74a.js';
4
- import 'svelte/store';
1
+ import { Readable, Writable } from 'svelte/store';
2
+
3
+ /**
4
+ * Shared types between the API and UI packages.
5
+ */
6
+ type Message = {
7
+ id: string;
8
+ createdAt?: Date;
9
+ content: string;
10
+ role: 'system' | 'user' | 'assistant';
11
+ };
12
+ type CreateMessage = {
13
+ id?: string;
14
+ createdAt?: Date;
15
+ content: string;
16
+ role: 'system' | 'user' | 'assistant';
17
+ };
18
+ type UseChatOptions = {
19
+ /**
20
+ * The API endpoint that accepts a `{ messages: Message[] }` object and returns
21
+ * a stream of tokens of the AI chat response. Defaults to `/api/chat`.
22
+ */
23
+ api?: string;
24
+ /**
25
+ * An unique identifier for the chat. If not provided, a random one will be
26
+ * generated. When provided, the `useChat` hook with the same `id` will
27
+ * have shared states across components.
28
+ */
29
+ id?: string;
30
+ /**
31
+ * Initial messages of the chat. Useful to load an existing chat history.
32
+ */
33
+ initialMessages?: Message[];
34
+ /**
35
+ * Initial input of the chat.
36
+ */
37
+ initialInput?: string;
38
+ /**
39
+ * Callback function to be called when the API response is received.
40
+ */
41
+ onResponse?: (response: Response) => void;
42
+ /**
43
+ * Callback function to be called when the chat is finished streaming.
44
+ */
45
+ onFinish?: (message: Message) => void;
46
+ /**
47
+ * Callback function to be called when an error is encountered.
48
+ */
49
+ onError?: (error: Error) => void;
50
+ /**
51
+ * HTTP headers to be sent with the API request.
52
+ */
53
+ headers?: Record<string, string> | Headers;
54
+ /**
55
+ * Extra body object to be sent with the API request.
56
+ * @example
57
+ * Send a `sessionId` to the API along with the messages.
58
+ * ```js
59
+ * useChat({
60
+ * body: {
61
+ * sessionId: '123',
62
+ * }
63
+ * })
64
+ * ```
65
+ */
66
+ body?: object;
67
+ /**
68
+ * Whether to send extra message fields such as `message.id` and `message.createdAt` to the API.
69
+ * Defaults to `false`. When set to `true`, the API endpoint might need to
70
+ * handle the extra fields before forwarding the request to the AI service.
71
+ */
72
+ sendExtraMessageFields?: boolean;
73
+ };
74
+ type UseCompletionOptions = {
75
+ /**
76
+ * The API endpoint that accepts a `{ prompt: string }` object and returns
77
+ * a stream of tokens of the AI completion response. Defaults to `/api/completion`.
78
+ */
79
+ api?: string;
80
+ /**
81
+ * An unique identifier for the chat. If not provided, a random one will be
82
+ * generated. When provided, the `useChat` hook with the same `id` will
83
+ * have shared states across components.
84
+ */
85
+ id?: string;
86
+ /**
87
+ * Initial prompt input of the completion.
88
+ */
89
+ initialInput?: string;
90
+ /**
91
+ * Initial completion result. Useful to load an existing history.
92
+ */
93
+ initialCompletion?: string;
94
+ /**
95
+ * Callback function to be called when the API response is received.
96
+ */
97
+ onResponse?: (response: Response) => void;
98
+ /**
99
+ * Callback function to be called when the completion is finished streaming.
100
+ */
101
+ onFinish?: (prompt: string, completion: string) => void;
102
+ /**
103
+ * Callback function to be called when an error is encountered.
104
+ */
105
+ onError?: (error: Error) => void;
106
+ /**
107
+ * HTTP headers to be sent with the API request.
108
+ */
109
+ headers?: Record<string, string> | Headers;
110
+ /**
111
+ * Extra body object to be sent with the API request.
112
+ * @example
113
+ * Send a `sessionId` to the API along with the prompt.
114
+ * ```js
115
+ * useChat({
116
+ * body: {
117
+ * sessionId: '123',
118
+ * }
119
+ * })
120
+ * ```
121
+ */
122
+ body?: object;
123
+ };
124
+
125
+ type UseChatHelpers = {
126
+ /** Current messages in the chat */
127
+ messages: Readable<Message[]>;
128
+ /** The error object of the API request */
129
+ error: Readable<undefined | Error>;
130
+ /**
131
+ * Append a user message to the chat list. This triggers the API call to fetch
132
+ * the assistant's response.
133
+ */
134
+ append: (message: Message | CreateMessage) => Promise<string | null | undefined>;
135
+ /**
136
+ * Reload the last AI chat response for the given chat history. If the last
137
+ * message isn't from the assistant, it will request the API to generate a
138
+ * new response.
139
+ */
140
+ reload: () => Promise<string | null | undefined>;
141
+ /**
142
+ * Abort the current request immediately, keep the generated tokens if any.
143
+ */
144
+ stop: () => void;
145
+ /**
146
+ * Update the `messages` state locally. This is useful when you want to
147
+ * edit the messages on the client, and then trigger the `reload` method
148
+ * manually to regenerate the AI response.
149
+ */
150
+ setMessages: (messages: Message[]) => void;
151
+ /** The current value of the input */
152
+ input: Writable<string>;
153
+ /** Form submission handler to automattically reset input and append a user message */
154
+ handleSubmit: (e: any) => void;
155
+ /** Whether the API request is in progress */
156
+ isLoading: Writable<boolean>;
157
+ };
158
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onResponse, onFinish, onError, headers, body }?: UseChatOptions): UseChatHelpers;
159
+
160
+ type UseCompletionHelpers = {
161
+ /** The current completion result */
162
+ completion: Readable<string>;
163
+ /** The error object of the API request */
164
+ error: Readable<undefined | Error>;
165
+ /**
166
+ * Send a new prompt to the API endpoint and update the completion state.
167
+ */
168
+ complete: (prompt: string) => Promise<string | null | undefined>;
169
+ /**
170
+ * Abort the current API request but keep the generated tokens.
171
+ */
172
+ stop: () => void;
173
+ /**
174
+ * Update the `completion` state locally.
175
+ */
176
+ setCompletion: (completion: string) => void;
177
+ /** The current value of the input */
178
+ input: Writable<string>;
179
+ /**
180
+ * Form submission handler to automattically reset input and append a user message
181
+ * @example
182
+ * ```jsx
183
+ * <form onSubmit={handleSubmit}>
184
+ * <input onChange={handleInputChange} value={input} />
185
+ * </form>
186
+ * ```
187
+ */
188
+ handleSubmit: (e: any) => void;
189
+ /** Whether the API request is in progress */
190
+ isLoading: Writable<boolean>;
191
+ };
192
+ declare function useCompletion({ api, id, initialCompletion, initialInput, headers, body, onResponse, onFinish, onError }?: UseCompletionOptions): UseCompletionHelpers;
193
+
194
+ export { CreateMessage, Message, UseChatHelpers, UseChatOptions, UseCompletionHelpers, useChat, useCompletion };
@@ -659,7 +659,8 @@ function useChat({
659
659
  return;
660
660
  append({
661
661
  content: inputValue,
662
- role: "user"
662
+ role: "user",
663
+ createdAt: /* @__PURE__ */ new Date()
663
664
  });
664
665
  input.set("");
665
666
  };