ai 2.1.0 → 2.1.2

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 (68) hide show
  1. package/dist/index.d.ts +48 -8
  2. package/dist/index.mjs +234 -26
  3. package/package.json +4 -4
  4. package/react/dist/index.d.ts +206 -3
  5. package/react/dist/index.mjs +384 -7
  6. package/svelte/dist/index.d.ts +194 -4
  7. package/svelte/dist/index.mjs +779 -7
  8. package/vue/dist/index.d.ts +194 -4
  9. package/vue/dist/index.mjs +345 -7
  10. package/dist/ai-stream.d.ts +0 -18
  11. package/dist/ai-stream.js +0 -132
  12. package/dist/ai-stream.mjs +0 -15
  13. package/dist/anthropic-stream.d.ts +0 -5
  14. package/dist/anthropic-stream.js +0 -133
  15. package/dist/anthropic-stream.mjs +0 -10
  16. package/dist/chunk-2JQWCLY2.mjs +0 -70
  17. package/dist/chunk-7KLTYB74.mjs +0 -70
  18. package/dist/chunk-BJMBMGA3.mjs +0 -34
  19. package/dist/chunk-KKQRUR3E.mjs +0 -51
  20. package/dist/chunk-RBP6ONSV.mjs +0 -45
  21. package/dist/chunk-TWW2ODJW.mjs +0 -32
  22. package/dist/chunk-U2OQ6HW6.mjs +0 -41
  23. package/dist/chunk-UJV6VDVU.mjs +0 -97
  24. package/dist/huggingface-stream.d.ts +0 -5
  25. package/dist/huggingface-stream.js +0 -121
  26. package/dist/huggingface-stream.mjs +0 -10
  27. package/dist/index.test.d.ts +0 -2
  28. package/dist/index.test.js +0 -568
  29. package/dist/index.test.mjs +0 -286
  30. package/dist/langchain-stream.d.ts +0 -12
  31. package/dist/langchain-stream.js +0 -102
  32. package/dist/langchain-stream.mjs +0 -10
  33. package/dist/openai-stream.d.ts +0 -5
  34. package/dist/openai-stream.js +0 -144
  35. package/dist/openai-stream.mjs +0 -10
  36. package/dist/streaming-text-response.d.ts +0 -17
  37. package/dist/streaming-text-response.js +0 -75
  38. package/dist/streaming-text-response.mjs +0 -11
  39. package/react/dist/chunk-5PP6W52J.mjs +0 -202
  40. package/react/dist/chunk-6EH3SWMP.mjs +0 -55
  41. package/react/dist/chunk-PW6HSU2N.mjs +0 -154
  42. package/react/dist/types-f862f74a.d.ts +0 -123
  43. package/react/dist/use-chat.d.ts +0 -42
  44. package/react/dist/use-chat.js +0 -276
  45. package/react/dist/use-chat.mjs +0 -8
  46. package/react/dist/use-completion.d.ts +0 -47
  47. package/react/dist/use-completion.js +0 -229
  48. package/react/dist/use-completion.mjs +0 -8
  49. package/svelte/dist/chunk-6USBQIV6.mjs +0 -177
  50. package/svelte/dist/chunk-BQ64GHZ3.mjs +0 -136
  51. package/svelte/dist/chunk-CENOSGDG.mjs +0 -493
  52. package/svelte/dist/types-f862f74a.d.ts +0 -123
  53. package/svelte/dist/use-chat.d.ts +0 -39
  54. package/svelte/dist/use-chat.js +0 -680
  55. package/svelte/dist/use-chat.mjs +0 -7
  56. package/svelte/dist/use-completion.d.ts +0 -38
  57. package/svelte/dist/use-completion.js +0 -640
  58. package/svelte/dist/use-completion.mjs +0 -7
  59. package/vue/dist/chunk-FT26CHLO.mjs +0 -137
  60. package/vue/dist/chunk-OYI6GFBM.mjs +0 -178
  61. package/vue/dist/chunk-WXH4YPZV.mjs +0 -54
  62. package/vue/dist/types-f862f74a.d.ts +0 -123
  63. package/vue/dist/use-chat.d.ts +0 -39
  64. package/vue/dist/use-chat.js +0 -252
  65. package/vue/dist/use-chat.mjs +0 -7
  66. package/vue/dist/use-completion.d.ts +0 -38
  67. package/vue/dist/use-completion.js +0 -212
  68. package/vue/dist/use-completion.mjs +0 -7
@@ -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 'vue';
1
+ import { Ref } from 'vue';
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: Ref<Message[]>;
128
+ /** The error object of the API request */
129
+ error: Ref<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: Ref<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: Ref<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: Ref<string>;
163
+ /** The error object of the API request */
164
+ error: Ref<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: Ref<string>;
179
+ /**
180
+ * Form submission handler to automatically reset input and append a user message
181
+ * @example
182
+ * ```jsx
183
+ * <form @submit="handleSubmit">
184
+ * <input @change="handleInputChange" v-model="input" />
185
+ * </form>
186
+ * ```
187
+ */
188
+ handleSubmit: (e: any) => void;
189
+ /** Whether the API request is in progress */
190
+ isLoading: Ref<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 };
@@ -1,10 +1,348 @@
1
- import {
2
- useChat
3
- } from "./chunk-OYI6GFBM.mjs";
4
- import {
5
- useCompletion
6
- } from "./chunk-FT26CHLO.mjs";
7
- import "./chunk-WXH4YPZV.mjs";
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+
38
+ // vue/use-chat.ts
39
+ import swrv from "swrv";
40
+ import { ref } from "vue";
41
+
42
+ // shared/utils.ts
43
+ import { customAlphabet } from "nanoid";
44
+ var nanoid = customAlphabet(
45
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
46
+ 7
47
+ );
48
+ var decoder = new TextDecoder();
49
+ function decodeAIStreamChunk(chunk) {
50
+ return decoder.decode(chunk);
51
+ }
52
+
53
+ // vue/use-chat.ts
54
+ var uniqueId = 0;
55
+ var useSWRV = swrv.default || swrv;
56
+ var store = {};
57
+ function useChat({
58
+ api = "/api/chat",
59
+ id,
60
+ initialMessages = [],
61
+ initialInput = "",
62
+ sendExtraMessageFields,
63
+ onResponse,
64
+ onFinish,
65
+ onError,
66
+ headers,
67
+ body
68
+ } = {}) {
69
+ const chatId = id || `chat-${uniqueId++}`;
70
+ const key = `${api}|${chatId}`;
71
+ const { data, mutate: originalMutate } = useSWRV(
72
+ key,
73
+ () => store[key] || initialMessages
74
+ );
75
+ data.value || (data.value = initialMessages);
76
+ const mutate = (data2) => {
77
+ store[key] = data2;
78
+ return originalMutate();
79
+ };
80
+ const messages = data;
81
+ const error = ref(void 0);
82
+ const isLoading = ref(false);
83
+ let abortController = null;
84
+ function triggerRequest(messagesSnapshot) {
85
+ return __async(this, null, function* () {
86
+ try {
87
+ isLoading.value = true;
88
+ abortController = new AbortController();
89
+ const previousMessages = messages.value;
90
+ mutate(messagesSnapshot);
91
+ const res = yield fetch(api, {
92
+ method: "POST",
93
+ body: JSON.stringify(__spreadValues({
94
+ messages: sendExtraMessageFields ? messagesSnapshot : messagesSnapshot.map(({ role, content }) => ({
95
+ role,
96
+ content
97
+ }))
98
+ }, body)),
99
+ headers: headers || {},
100
+ signal: abortController.signal
101
+ }).catch((err) => {
102
+ mutate(previousMessages);
103
+ throw err;
104
+ });
105
+ if (onResponse) {
106
+ try {
107
+ yield onResponse(res);
108
+ } catch (err) {
109
+ throw err;
110
+ }
111
+ }
112
+ if (!res.ok) {
113
+ mutate(previousMessages);
114
+ throw new Error(
115
+ (yield res.text()) || "Failed to fetch the chat response."
116
+ );
117
+ }
118
+ if (!res.body) {
119
+ throw new Error("The response body is empty.");
120
+ }
121
+ let result = "";
122
+ const createdAt = /* @__PURE__ */ new Date();
123
+ const replyId = nanoid();
124
+ const reader = res.body.getReader();
125
+ while (true) {
126
+ const { done, value } = yield reader.read();
127
+ if (done) {
128
+ break;
129
+ }
130
+ result += decodeAIStreamChunk(value);
131
+ mutate([
132
+ ...messagesSnapshot,
133
+ {
134
+ id: replyId,
135
+ createdAt,
136
+ content: result,
137
+ role: "assistant"
138
+ }
139
+ ]);
140
+ if (abortController === null) {
141
+ reader.cancel();
142
+ break;
143
+ }
144
+ }
145
+ if (onFinish) {
146
+ onFinish({
147
+ id: replyId,
148
+ createdAt,
149
+ content: result,
150
+ role: "assistant"
151
+ });
152
+ }
153
+ abortController = null;
154
+ return result;
155
+ } catch (err) {
156
+ if (err.name === "AbortError") {
157
+ abortController = null;
158
+ return null;
159
+ }
160
+ if (onError && err instanceof Error) {
161
+ onError(err);
162
+ }
163
+ error.value = err;
164
+ } finally {
165
+ isLoading.value = false;
166
+ }
167
+ });
168
+ }
169
+ const append = (message) => __async(this, null, function* () {
170
+ if (!message.id) {
171
+ message.id = nanoid();
172
+ }
173
+ return triggerRequest(messages.value.concat(message));
174
+ });
175
+ const reload = () => __async(this, null, function* () {
176
+ const messagesSnapshot = messages.value;
177
+ if (messagesSnapshot.length === 0)
178
+ return null;
179
+ const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
180
+ if (lastMessage.role === "assistant") {
181
+ return triggerRequest(messagesSnapshot.slice(0, -1));
182
+ }
183
+ return triggerRequest(messagesSnapshot);
184
+ });
185
+ const stop = () => {
186
+ if (abortController) {
187
+ abortController.abort();
188
+ abortController = null;
189
+ }
190
+ };
191
+ const setMessages = (messages2) => {
192
+ mutate(messages2);
193
+ };
194
+ const input = ref(initialInput);
195
+ const handleSubmit = (e) => {
196
+ e.preventDefault();
197
+ const inputValue = input.value;
198
+ if (!inputValue)
199
+ return;
200
+ append({
201
+ content: inputValue,
202
+ role: "user"
203
+ });
204
+ input.value = "";
205
+ };
206
+ return {
207
+ messages,
208
+ append,
209
+ error,
210
+ reload,
211
+ stop,
212
+ setMessages,
213
+ input,
214
+ handleSubmit,
215
+ isLoading
216
+ };
217
+ }
218
+
219
+ // vue/use-completion.ts
220
+ import swrv2 from "swrv";
221
+ import { ref as ref2 } from "vue";
222
+ var uniqueId2 = 0;
223
+ var useSWRV2 = swrv2.default || swrv2;
224
+ var store2 = {};
225
+ function useCompletion({
226
+ api = "/api/completion",
227
+ id,
228
+ initialCompletion = "",
229
+ initialInput = "",
230
+ headers,
231
+ body,
232
+ onResponse,
233
+ onFinish,
234
+ onError
235
+ } = {}) {
236
+ const completionId = id || `completion-${uniqueId2++}`;
237
+ const key = `${api}|${completionId}`;
238
+ const { data, mutate: originalMutate } = useSWRV2(
239
+ key,
240
+ () => store2[key] || initialCompletion
241
+ );
242
+ data.value || (data.value = initialCompletion);
243
+ const mutate = (data2) => {
244
+ store2[key] = data2;
245
+ return originalMutate();
246
+ };
247
+ const completion = data;
248
+ const error = ref2(void 0);
249
+ const isLoading = ref2(false);
250
+ let abortController = null;
251
+ function triggerRequest(prompt) {
252
+ return __async(this, null, function* () {
253
+ try {
254
+ isLoading.value = true;
255
+ abortController = new AbortController();
256
+ mutate("");
257
+ const res = yield fetch(api, {
258
+ method: "POST",
259
+ body: JSON.stringify(__spreadValues({
260
+ prompt
261
+ }, body)),
262
+ headers: headers || {},
263
+ signal: abortController.signal
264
+ }).catch((err) => {
265
+ throw err;
266
+ });
267
+ if (onResponse) {
268
+ try {
269
+ yield onResponse(res);
270
+ } catch (err) {
271
+ throw err;
272
+ }
273
+ }
274
+ if (!res.ok) {
275
+ throw new Error(
276
+ (yield res.text()) || "Failed to fetch the chat response."
277
+ );
278
+ }
279
+ if (!res.body) {
280
+ throw new Error("The response body is empty.");
281
+ }
282
+ let result = "";
283
+ const reader = res.body.getReader();
284
+ while (true) {
285
+ const { done, value } = yield reader.read();
286
+ if (done) {
287
+ break;
288
+ }
289
+ result += decodeAIStreamChunk(value);
290
+ mutate(result);
291
+ if (abortController === null) {
292
+ reader.cancel();
293
+ break;
294
+ }
295
+ }
296
+ if (onFinish) {
297
+ onFinish(prompt, result);
298
+ }
299
+ abortController = null;
300
+ return result;
301
+ } catch (err) {
302
+ if (err.name === "AbortError") {
303
+ abortController = null;
304
+ return null;
305
+ }
306
+ if (onError && error instanceof Error) {
307
+ onError(error);
308
+ }
309
+ error.value = err;
310
+ } finally {
311
+ isLoading.value = false;
312
+ }
313
+ });
314
+ }
315
+ const complete = (prompt) => __async(this, null, function* () {
316
+ return triggerRequest(prompt);
317
+ });
318
+ const stop = () => {
319
+ if (abortController) {
320
+ abortController.abort();
321
+ abortController = null;
322
+ }
323
+ };
324
+ const setCompletion = (completion2) => {
325
+ mutate(completion2);
326
+ };
327
+ const input = ref2(initialInput);
328
+ const handleSubmit = (e) => {
329
+ e.preventDefault();
330
+ const inputValue = input.value;
331
+ if (!inputValue)
332
+ return;
333
+ return complete(inputValue);
334
+ };
335
+ return {
336
+ completion,
337
+ complete,
338
+ error,
339
+ stop,
340
+ setCompletion,
341
+ input,
342
+ handleSubmit,
343
+ isLoading
344
+ };
345
+ }
8
346
  export {
9
347
  useChat,
10
348
  useCompletion
@@ -1,18 +0,0 @@
1
- interface AIStreamCallbacks {
2
- onStart?: () => Promise<void>;
3
- onCompletion?: (completion: string) => Promise<void>;
4
- onToken?: (token: string) => Promise<void>;
5
- }
6
- interface AIStreamParser {
7
- (data: string): string | void;
8
- }
9
- declare function createEventStreamTransformer(customParser: AIStreamParser): TransformStream<Uint8Array, string>;
10
- /**
11
- * This stream forks input stream, allowing us to use the result as a
12
- * bytestream of the messages and pass the messages to our callback interface.
13
- */
14
- declare function createCallbacksTransformer(callbacks: AIStreamCallbacks | undefined): TransformStream<string, Uint8Array>;
15
- declare function trimStartOfStreamHelper(): (text: string) => string;
16
- declare function AIStream(res: Response, customParser: AIStreamParser, callbacks?: AIStreamCallbacks): ReadableStream;
17
-
18
- export { AIStream, AIStreamCallbacks, AIStreamParser, createCallbacksTransformer, createEventStreamTransformer, trimStartOfStreamHelper };
package/dist/ai-stream.js DELETED
@@ -1,132 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var __async = (__this, __arguments, generator) => {
20
- return new Promise((resolve, reject) => {
21
- var fulfilled = (value) => {
22
- try {
23
- step(generator.next(value));
24
- } catch (e) {
25
- reject(e);
26
- }
27
- };
28
- var rejected = (value) => {
29
- try {
30
- step(generator.throw(value));
31
- } catch (e) {
32
- reject(e);
33
- }
34
- };
35
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
36
- step((generator = generator.apply(__this, __arguments)).next());
37
- });
38
- };
39
-
40
- // streams/ai-stream.ts
41
- var ai_stream_exports = {};
42
- __export(ai_stream_exports, {
43
- AIStream: () => AIStream,
44
- createCallbacksTransformer: () => createCallbacksTransformer,
45
- createEventStreamTransformer: () => createEventStreamTransformer,
46
- trimStartOfStreamHelper: () => trimStartOfStreamHelper
47
- });
48
- module.exports = __toCommonJS(ai_stream_exports);
49
- var import_eventsource_parser = require("eventsource-parser");
50
- function createEventStreamTransformer(customParser) {
51
- const decoder = new TextDecoder();
52
- let parser;
53
- return new TransformStream({
54
- start(controller) {
55
- return __async(this, null, function* () {
56
- function onParse(event) {
57
- if (event.type === "event") {
58
- const data = event.data;
59
- if (data === "[DONE]") {
60
- controller.terminate();
61
- return;
62
- }
63
- const message = customParser(data);
64
- if (message)
65
- controller.enqueue(message);
66
- }
67
- }
68
- parser = (0, import_eventsource_parser.createParser)(onParse);
69
- });
70
- },
71
- transform(chunk) {
72
- parser.feed(decoder.decode(chunk));
73
- }
74
- });
75
- }
76
- function createCallbacksTransformer(callbacks) {
77
- const encoder = new TextEncoder();
78
- let fullResponse = "";
79
- const { onStart, onToken, onCompletion } = callbacks || {};
80
- return new TransformStream({
81
- start() {
82
- return __async(this, null, function* () {
83
- if (onStart)
84
- yield onStart();
85
- });
86
- },
87
- transform(message, controller) {
88
- return __async(this, null, function* () {
89
- controller.enqueue(encoder.encode(message));
90
- if (onToken)
91
- yield onToken(message);
92
- if (onCompletion)
93
- fullResponse += message;
94
- });
95
- },
96
- flush() {
97
- return __async(this, null, function* () {
98
- yield onCompletion == null ? void 0 : onCompletion(fullResponse);
99
- });
100
- }
101
- });
102
- }
103
- function trimStartOfStreamHelper() {
104
- let start = true;
105
- return (text) => {
106
- if (start)
107
- text = text.trimStart();
108
- if (text)
109
- start = false;
110
- return text;
111
- };
112
- }
113
- function AIStream(res, customParser, callbacks) {
114
- if (!res.ok) {
115
- throw new Error(
116
- `Failed to convert the response to stream. Received status code: ${res.status}.`
117
- );
118
- }
119
- const stream = res.body || new ReadableStream({
120
- start(controller) {
121
- controller.close();
122
- }
123
- });
124
- return stream.pipeThrough(createEventStreamTransformer(customParser)).pipeThrough(createCallbacksTransformer(callbacks));
125
- }
126
- // Annotate the CommonJS export names for ESM import in node:
127
- 0 && (module.exports = {
128
- AIStream,
129
- createCallbacksTransformer,
130
- createEventStreamTransformer,
131
- trimStartOfStreamHelper
132
- });