ai 2.0.0 → 2.1.0

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 (34) hide show
  1. package/dist/ai-stream.mjs +4 -2
  2. package/dist/anthropic-stream.mjs +6 -4
  3. package/dist/chunk-2JQWCLY2.mjs +70 -0
  4. package/dist/chunk-7KLTYB74.mjs +70 -0
  5. package/dist/{chunk-TJMME6CL.mjs → chunk-BJMBMGA3.mjs} +12 -2
  6. package/dist/{chunk-PEYAHBDF.mjs → chunk-KKQRUR3E.mjs} +12 -4
  7. package/dist/{chunk-NK2CVBLI.mjs → chunk-RBP6ONSV.mjs} +19 -12
  8. package/dist/{chunk-JGDC3BXD.mjs → chunk-TWW2ODJW.mjs} +13 -3
  9. package/dist/{chunk-EZJ7FC5E.mjs → chunk-U2OQ6HW6.mjs} +14 -6
  10. package/dist/{chunk-265FSSO4.mjs → chunk-UJV6VDVU.mjs} +9 -3
  11. package/dist/huggingface-stream.mjs +6 -4
  12. package/dist/index.js +1 -1
  13. package/dist/index.mjs +11 -7
  14. package/dist/index.test.js +562 -6
  15. package/dist/index.test.mjs +283 -7
  16. package/dist/langchain-stream.d.ts +1 -1
  17. package/dist/langchain-stream.js +1 -1
  18. package/dist/langchain-stream.mjs +6 -4
  19. package/dist/openai-stream.mjs +6 -4
  20. package/dist/streaming-text-response.mjs +4 -2
  21. package/package.json +18 -6
  22. package/vue/dist/chunk-FT26CHLO.mjs +137 -0
  23. package/vue/dist/chunk-OYI6GFBM.mjs +178 -0
  24. package/{dist/chunk-2L3ZO4UM.mjs → vue/dist/chunk-WXH4YPZV.mjs} +14 -5
  25. package/vue/dist/index.d.ts +4 -0
  26. package/vue/dist/index.js +384 -0
  27. package/vue/dist/index.mjs +11 -0
  28. package/vue/dist/types-f862f74a.d.ts +123 -0
  29. package/vue/dist/use-chat.d.ts +39 -0
  30. package/vue/dist/use-chat.js +252 -0
  31. package/vue/dist/use-chat.mjs +7 -0
  32. package/vue/dist/use-completion.d.ts +38 -0
  33. package/vue/dist/use-completion.js +212 -0
  34. package/vue/dist/use-completion.mjs +7 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Shared types between the API and UI packages.
3
+ */
4
+ type Message = {
5
+ id: string;
6
+ createdAt?: Date;
7
+ content: string;
8
+ role: 'system' | 'user' | 'assistant';
9
+ };
10
+ type CreateMessage = {
11
+ id?: string;
12
+ createdAt?: Date;
13
+ content: string;
14
+ role: 'system' | 'user' | 'assistant';
15
+ };
16
+ type UseChatOptions = {
17
+ /**
18
+ * The API endpoint that accepts a `{ messages: Message[] }` object and returns
19
+ * a stream of tokens of the AI chat response. Defaults to `/api/chat`.
20
+ */
21
+ api?: string;
22
+ /**
23
+ * An unique identifier for the chat. If not provided, a random one will be
24
+ * generated. When provided, the `useChat` hook with the same `id` will
25
+ * have shared states across components.
26
+ */
27
+ id?: string;
28
+ /**
29
+ * Initial messages of the chat. Useful to load an existing chat history.
30
+ */
31
+ initialMessages?: Message[];
32
+ /**
33
+ * Initial input of the chat.
34
+ */
35
+ initialInput?: string;
36
+ /**
37
+ * Callback function to be called when the API response is received.
38
+ */
39
+ onResponse?: (response: Response) => void;
40
+ /**
41
+ * Callback function to be called when the chat is finished streaming.
42
+ */
43
+ onFinish?: (message: Message) => void;
44
+ /**
45
+ * Callback function to be called when an error is encountered.
46
+ */
47
+ onError?: (error: Error) => void;
48
+ /**
49
+ * HTTP headers to be sent with the API request.
50
+ */
51
+ headers?: Record<string, string> | Headers;
52
+ /**
53
+ * Extra body object to be sent with the API request.
54
+ * @example
55
+ * Send a `sessionId` to the API along with the messages.
56
+ * ```js
57
+ * useChat({
58
+ * body: {
59
+ * sessionId: '123',
60
+ * }
61
+ * })
62
+ * ```
63
+ */
64
+ body?: object;
65
+ /**
66
+ * Whether to send extra message fields such as `message.id` and `message.createdAt` to the API.
67
+ * Defaults to `false`. When set to `true`, the API endpoint might need to
68
+ * handle the extra fields before forwarding the request to the AI service.
69
+ */
70
+ sendExtraMessageFields?: boolean;
71
+ };
72
+ type UseCompletionOptions = {
73
+ /**
74
+ * The API endpoint that accepts a `{ prompt: string }` object and returns
75
+ * a stream of tokens of the AI completion response. Defaults to `/api/completion`.
76
+ */
77
+ api?: string;
78
+ /**
79
+ * An unique identifier for the chat. If not provided, a random one will be
80
+ * generated. When provided, the `useChat` hook with the same `id` will
81
+ * have shared states across components.
82
+ */
83
+ id?: string;
84
+ /**
85
+ * Initial prompt input of the completion.
86
+ */
87
+ initialInput?: string;
88
+ /**
89
+ * Initial completion result. Useful to load an existing history.
90
+ */
91
+ initialCompletion?: string;
92
+ /**
93
+ * Callback function to be called when the API response is received.
94
+ */
95
+ onResponse?: (response: Response) => void;
96
+ /**
97
+ * Callback function to be called when the completion is finished streaming.
98
+ */
99
+ onFinish?: (prompt: string, completion: string) => void;
100
+ /**
101
+ * Callback function to be called when an error is encountered.
102
+ */
103
+ onError?: (error: Error) => void;
104
+ /**
105
+ * HTTP headers to be sent with the API request.
106
+ */
107
+ headers?: Record<string, string> | Headers;
108
+ /**
109
+ * Extra body object to be sent with the API request.
110
+ * @example
111
+ * Send a `sessionId` to the API along with the prompt.
112
+ * ```js
113
+ * useChat({
114
+ * body: {
115
+ * sessionId: '123',
116
+ * }
117
+ * })
118
+ * ```
119
+ */
120
+ body?: object;
121
+ };
122
+
123
+ export { CreateMessage as C, Message as M, UseChatOptions as U, UseCompletionOptions as a };
@@ -0,0 +1,39 @@
1
+ import { Ref } from 'vue';
2
+ import { M as Message, C as CreateMessage, U as UseChatOptions } from './types-f862f74a.js';
3
+
4
+ type UseChatHelpers = {
5
+ /** Current messages in the chat */
6
+ messages: Ref<Message[]>;
7
+ /** The error object of the API request */
8
+ error: Ref<undefined | Error>;
9
+ /**
10
+ * Append a user message to the chat list. This triggers the API call to fetch
11
+ * the assistant's response.
12
+ */
13
+ append: (message: Message | CreateMessage) => Promise<string | null | undefined>;
14
+ /**
15
+ * Reload the last AI chat response for the given chat history. If the last
16
+ * message isn't from the assistant, it will request the API to generate a
17
+ * new response.
18
+ */
19
+ reload: () => Promise<string | null | undefined>;
20
+ /**
21
+ * Abort the current request immediately, keep the generated tokens if any.
22
+ */
23
+ stop: () => void;
24
+ /**
25
+ * Update the `messages` state locally. This is useful when you want to
26
+ * edit the messages on the client, and then trigger the `reload` method
27
+ * manually to regenerate the AI response.
28
+ */
29
+ setMessages: (messages: Message[]) => void;
30
+ /** The current value of the input */
31
+ input: Ref<string>;
32
+ /** Form submission handler to automattically reset input and append a user message */
33
+ handleSubmit: (e: any) => void;
34
+ /** Whether the API request is in progress */
35
+ isLoading: Ref<boolean>;
36
+ };
37
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onResponse, onFinish, onError, headers, body }?: UseChatOptions): UseChatHelpers;
38
+
39
+ export { CreateMessage, Message, UseChatHelpers, UseChatOptions, useChat };
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+ var __async = (__this, __arguments, generator) => {
44
+ return new Promise((resolve, reject) => {
45
+ var fulfilled = (value) => {
46
+ try {
47
+ step(generator.next(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var rejected = (value) => {
53
+ try {
54
+ step(generator.throw(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
+ step((generator = generator.apply(__this, __arguments)).next());
61
+ });
62
+ };
63
+
64
+ // vue/use-chat.ts
65
+ var use_chat_exports = {};
66
+ __export(use_chat_exports, {
67
+ useChat: () => useChat
68
+ });
69
+ module.exports = __toCommonJS(use_chat_exports);
70
+ var import_swrv = __toESM(require("swrv"));
71
+ var import_vue = require("vue");
72
+
73
+ // shared/utils.ts
74
+ var import_nanoid = require("nanoid");
75
+ var nanoid = (0, import_nanoid.customAlphabet)(
76
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
77
+ 7
78
+ );
79
+ var decoder = new TextDecoder();
80
+ function decodeAIStreamChunk(chunk) {
81
+ return decoder.decode(chunk);
82
+ }
83
+
84
+ // vue/use-chat.ts
85
+ var uniqueId = 0;
86
+ var useSWRV = import_swrv.default.default || import_swrv.default;
87
+ var store = {};
88
+ function useChat({
89
+ api = "/api/chat",
90
+ id,
91
+ initialMessages = [],
92
+ initialInput = "",
93
+ sendExtraMessageFields,
94
+ onResponse,
95
+ onFinish,
96
+ onError,
97
+ headers,
98
+ body
99
+ } = {}) {
100
+ const chatId = id || `chat-${uniqueId++}`;
101
+ const key = `${api}|${chatId}`;
102
+ const { data, mutate: originalMutate } = useSWRV(
103
+ key,
104
+ () => store[key] || initialMessages
105
+ );
106
+ data.value || (data.value = initialMessages);
107
+ const mutate = (data2) => {
108
+ store[key] = data2;
109
+ return originalMutate();
110
+ };
111
+ const messages = data;
112
+ const error = (0, import_vue.ref)(void 0);
113
+ const isLoading = (0, import_vue.ref)(false);
114
+ let abortController = null;
115
+ function triggerRequest(messagesSnapshot) {
116
+ return __async(this, null, function* () {
117
+ try {
118
+ isLoading.value = true;
119
+ abortController = new AbortController();
120
+ const previousMessages = messages.value;
121
+ mutate(messagesSnapshot);
122
+ const res = yield fetch(api, {
123
+ method: "POST",
124
+ body: JSON.stringify(__spreadValues({
125
+ messages: sendExtraMessageFields ? messagesSnapshot : messagesSnapshot.map(({ role, content }) => ({
126
+ role,
127
+ content
128
+ }))
129
+ }, body)),
130
+ headers: headers || {},
131
+ signal: abortController.signal
132
+ }).catch((err) => {
133
+ mutate(previousMessages);
134
+ throw err;
135
+ });
136
+ if (onResponse) {
137
+ try {
138
+ yield onResponse(res);
139
+ } catch (err) {
140
+ throw err;
141
+ }
142
+ }
143
+ if (!res.ok) {
144
+ mutate(previousMessages);
145
+ throw new Error(
146
+ (yield res.text()) || "Failed to fetch the chat response."
147
+ );
148
+ }
149
+ if (!res.body) {
150
+ throw new Error("The response body is empty.");
151
+ }
152
+ let result = "";
153
+ const createdAt = /* @__PURE__ */ new Date();
154
+ const replyId = nanoid();
155
+ const reader = res.body.getReader();
156
+ while (true) {
157
+ const { done, value } = yield reader.read();
158
+ if (done) {
159
+ break;
160
+ }
161
+ result += decodeAIStreamChunk(value);
162
+ mutate([
163
+ ...messagesSnapshot,
164
+ {
165
+ id: replyId,
166
+ createdAt,
167
+ content: result,
168
+ role: "assistant"
169
+ }
170
+ ]);
171
+ if (abortController === null) {
172
+ reader.cancel();
173
+ break;
174
+ }
175
+ }
176
+ if (onFinish) {
177
+ onFinish({
178
+ id: replyId,
179
+ createdAt,
180
+ content: result,
181
+ role: "assistant"
182
+ });
183
+ }
184
+ abortController = null;
185
+ return result;
186
+ } catch (err) {
187
+ if (err.name === "AbortError") {
188
+ abortController = null;
189
+ return null;
190
+ }
191
+ if (onError && err instanceof Error) {
192
+ onError(err);
193
+ }
194
+ error.value = err;
195
+ } finally {
196
+ isLoading.value = false;
197
+ }
198
+ });
199
+ }
200
+ const append = (message) => __async(this, null, function* () {
201
+ if (!message.id) {
202
+ message.id = nanoid();
203
+ }
204
+ return triggerRequest(messages.value.concat(message));
205
+ });
206
+ const reload = () => __async(this, null, function* () {
207
+ const messagesSnapshot = messages.value;
208
+ if (messagesSnapshot.length === 0)
209
+ return null;
210
+ const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
211
+ if (lastMessage.role === "assistant") {
212
+ return triggerRequest(messagesSnapshot.slice(0, -1));
213
+ }
214
+ return triggerRequest(messagesSnapshot);
215
+ });
216
+ const stop = () => {
217
+ if (abortController) {
218
+ abortController.abort();
219
+ abortController = null;
220
+ }
221
+ };
222
+ const setMessages = (messages2) => {
223
+ mutate(messages2);
224
+ };
225
+ const input = (0, import_vue.ref)(initialInput);
226
+ const handleSubmit = (e) => {
227
+ e.preventDefault();
228
+ const inputValue = input.value;
229
+ if (!inputValue)
230
+ return;
231
+ append({
232
+ content: inputValue,
233
+ role: "user"
234
+ });
235
+ input.value = "";
236
+ };
237
+ return {
238
+ messages,
239
+ append,
240
+ error,
241
+ reload,
242
+ stop,
243
+ setMessages,
244
+ input,
245
+ handleSubmit,
246
+ isLoading
247
+ };
248
+ }
249
+ // Annotate the CommonJS export names for ESM import in node:
250
+ 0 && (module.exports = {
251
+ useChat
252
+ });
@@ -0,0 +1,7 @@
1
+ import {
2
+ useChat
3
+ } from "./chunk-OYI6GFBM.mjs";
4
+ import "./chunk-WXH4YPZV.mjs";
5
+ export {
6
+ useChat
7
+ };
@@ -0,0 +1,38 @@
1
+ import { Ref } from 'vue';
2
+ import { a as UseCompletionOptions } from './types-f862f74a.js';
3
+
4
+ type UseCompletionHelpers = {
5
+ /** The current completion result */
6
+ completion: Ref<string>;
7
+ /** The error object of the API request */
8
+ error: Ref<undefined | Error>;
9
+ /**
10
+ * Send a new prompt to the API endpoint and update the completion state.
11
+ */
12
+ complete: (prompt: string) => Promise<string | null | undefined>;
13
+ /**
14
+ * Abort the current API request but keep the generated tokens.
15
+ */
16
+ stop: () => void;
17
+ /**
18
+ * Update the `completion` state locally.
19
+ */
20
+ setCompletion: (completion: string) => void;
21
+ /** The current value of the input */
22
+ input: Ref<string>;
23
+ /**
24
+ * Form submission handler to automatically reset input and append a user message
25
+ * @example
26
+ * ```jsx
27
+ * <form @submit="handleSubmit">
28
+ * <input @change="handleInputChange" v-model="input" />
29
+ * </form>
30
+ * ```
31
+ */
32
+ handleSubmit: (e: any) => void;
33
+ /** Whether the API request is in progress */
34
+ isLoading: Ref<boolean>;
35
+ };
36
+ declare function useCompletion({ api, id, initialCompletion, initialInput, headers, body, onResponse, onFinish, onError }?: UseCompletionOptions): UseCompletionHelpers;
37
+
38
+ export { UseCompletionHelpers, useCompletion };
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __export = (target, all) => {
23
+ for (var name in all)
24
+ __defProp(target, name, { get: all[name], enumerable: true });
25
+ };
26
+ var __copyProps = (to, from, except, desc) => {
27
+ if (from && typeof from === "object" || typeof from === "function") {
28
+ for (let key of __getOwnPropNames(from))
29
+ if (!__hasOwnProp.call(to, key) && key !== except)
30
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
+ // If the importer is in node compatibility mode or this is not an ESM
36
+ // file that has been converted to a CommonJS file using a Babel-
37
+ // compatible transform (i.e. "__esModule" has not been set), then set
38
+ // "default" to the CommonJS "module.exports" for node compatibility.
39
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
+ mod
41
+ ));
42
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+ var __async = (__this, __arguments, generator) => {
44
+ return new Promise((resolve, reject) => {
45
+ var fulfilled = (value) => {
46
+ try {
47
+ step(generator.next(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var rejected = (value) => {
53
+ try {
54
+ step(generator.throw(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
+ step((generator = generator.apply(__this, __arguments)).next());
61
+ });
62
+ };
63
+
64
+ // vue/use-completion.ts
65
+ var use_completion_exports = {};
66
+ __export(use_completion_exports, {
67
+ useCompletion: () => useCompletion
68
+ });
69
+ module.exports = __toCommonJS(use_completion_exports);
70
+ var import_swrv = __toESM(require("swrv"));
71
+ var import_vue = require("vue");
72
+
73
+ // shared/utils.ts
74
+ var import_nanoid = require("nanoid");
75
+ var nanoid = (0, import_nanoid.customAlphabet)(
76
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
77
+ 7
78
+ );
79
+ var decoder = new TextDecoder();
80
+ function decodeAIStreamChunk(chunk) {
81
+ return decoder.decode(chunk);
82
+ }
83
+
84
+ // vue/use-completion.ts
85
+ var uniqueId = 0;
86
+ var useSWRV = import_swrv.default.default || import_swrv.default;
87
+ var store = {};
88
+ function useCompletion({
89
+ api = "/api/completion",
90
+ id,
91
+ initialCompletion = "",
92
+ initialInput = "",
93
+ headers,
94
+ body,
95
+ onResponse,
96
+ onFinish,
97
+ onError
98
+ } = {}) {
99
+ const completionId = id || `completion-${uniqueId++}`;
100
+ const key = `${api}|${completionId}`;
101
+ const { data, mutate: originalMutate } = useSWRV(
102
+ key,
103
+ () => store[key] || initialCompletion
104
+ );
105
+ data.value || (data.value = initialCompletion);
106
+ const mutate = (data2) => {
107
+ store[key] = data2;
108
+ return originalMutate();
109
+ };
110
+ const completion = data;
111
+ const error = (0, import_vue.ref)(void 0);
112
+ const isLoading = (0, import_vue.ref)(false);
113
+ let abortController = null;
114
+ function triggerRequest(prompt) {
115
+ return __async(this, null, function* () {
116
+ try {
117
+ isLoading.value = true;
118
+ abortController = new AbortController();
119
+ mutate("");
120
+ const res = yield fetch(api, {
121
+ method: "POST",
122
+ body: JSON.stringify(__spreadValues({
123
+ prompt
124
+ }, body)),
125
+ headers: headers || {},
126
+ signal: abortController.signal
127
+ }).catch((err) => {
128
+ throw err;
129
+ });
130
+ if (onResponse) {
131
+ try {
132
+ yield onResponse(res);
133
+ } catch (err) {
134
+ throw err;
135
+ }
136
+ }
137
+ if (!res.ok) {
138
+ throw new Error(
139
+ (yield res.text()) || "Failed to fetch the chat response."
140
+ );
141
+ }
142
+ if (!res.body) {
143
+ throw new Error("The response body is empty.");
144
+ }
145
+ let result = "";
146
+ const reader = res.body.getReader();
147
+ while (true) {
148
+ const { done, value } = yield reader.read();
149
+ if (done) {
150
+ break;
151
+ }
152
+ result += decodeAIStreamChunk(value);
153
+ mutate(result);
154
+ if (abortController === null) {
155
+ reader.cancel();
156
+ break;
157
+ }
158
+ }
159
+ if (onFinish) {
160
+ onFinish(prompt, result);
161
+ }
162
+ abortController = null;
163
+ return result;
164
+ } catch (err) {
165
+ if (err.name === "AbortError") {
166
+ abortController = null;
167
+ return null;
168
+ }
169
+ if (onError && error instanceof Error) {
170
+ onError(error);
171
+ }
172
+ error.value = err;
173
+ } finally {
174
+ isLoading.value = false;
175
+ }
176
+ });
177
+ }
178
+ const complete = (prompt) => __async(this, null, function* () {
179
+ return triggerRequest(prompt);
180
+ });
181
+ const stop = () => {
182
+ if (abortController) {
183
+ abortController.abort();
184
+ abortController = null;
185
+ }
186
+ };
187
+ const setCompletion = (completion2) => {
188
+ mutate(completion2);
189
+ };
190
+ const input = (0, import_vue.ref)(initialInput);
191
+ const handleSubmit = (e) => {
192
+ e.preventDefault();
193
+ const inputValue = input.value;
194
+ if (!inputValue)
195
+ return;
196
+ return complete(inputValue);
197
+ };
198
+ return {
199
+ completion,
200
+ complete,
201
+ error,
202
+ stop,
203
+ setCompletion,
204
+ input,
205
+ handleSubmit,
206
+ isLoading
207
+ };
208
+ }
209
+ // Annotate the CommonJS export names for ESM import in node:
210
+ 0 && (module.exports = {
211
+ useCompletion
212
+ });
@@ -0,0 +1,7 @@
1
+ import {
2
+ useCompletion
3
+ } from "./chunk-FT26CHLO.mjs";
4
+ import "./chunk-WXH4YPZV.mjs";
5
+ export {
6
+ useCompletion
7
+ };