ai 2.1.23 → 2.1.24

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.
@@ -0,0 +1,411 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+
54
+ // solid/index.ts
55
+ var solid_exports = {};
56
+ __export(solid_exports, {
57
+ useChat: () => useChat,
58
+ useCompletion: () => useCompletion
59
+ });
60
+ module.exports = __toCommonJS(solid_exports);
61
+
62
+ // solid/use-chat.ts
63
+ var import_solid_js = require("solid-js");
64
+ var import_solid_swr_store = require("solid-swr-store");
65
+ var import_swr_store = require("swr-store");
66
+
67
+ // shared/utils.ts
68
+ var import_non_secure = require("nanoid/non-secure");
69
+ var nanoid = (0, import_non_secure.customAlphabet)(
70
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
71
+ 7
72
+ );
73
+ function createChunkDecoder() {
74
+ const decoder = new TextDecoder();
75
+ return function(chunk) {
76
+ if (!chunk)
77
+ return "";
78
+ return decoder.decode(chunk, { stream: true });
79
+ };
80
+ }
81
+
82
+ // solid/use-chat.ts
83
+ var uniqueId = 0;
84
+ var store = {};
85
+ var chatApiStore = (0, import_swr_store.createSWRStore)({
86
+ get: (key) => __async(void 0, null, function* () {
87
+ var _a;
88
+ return (_a = store[key]) != null ? _a : [];
89
+ })
90
+ });
91
+ function useChat({
92
+ api = "/api/chat",
93
+ id,
94
+ initialMessages = [],
95
+ initialInput = "",
96
+ sendExtraMessageFields,
97
+ onResponse,
98
+ onFinish,
99
+ onError,
100
+ credentials,
101
+ headers,
102
+ body
103
+ } = {}) {
104
+ const chatId = id || `chat-${uniqueId++}`;
105
+ const key = `${api}|${chatId}`;
106
+ const data = (0, import_solid_swr_store.useSWRStore)(chatApiStore, () => [key], {
107
+ initialData: initialMessages
108
+ });
109
+ const mutate = (data2) => {
110
+ store[key] = data2;
111
+ return chatApiStore.mutate([key], {
112
+ status: "success",
113
+ data: data2
114
+ });
115
+ };
116
+ const messages = data;
117
+ const [error, setError] = (0, import_solid_js.createSignal)(void 0);
118
+ const [isLoading, setIsLoading] = (0, import_solid_js.createSignal)(false);
119
+ let abortController = null;
120
+ function triggerRequest(messagesSnapshot, options) {
121
+ return __async(this, null, function* () {
122
+ try {
123
+ setIsLoading(true);
124
+ abortController = new AbortController();
125
+ const previousMessages = chatApiStore.get([key], {
126
+ shouldRevalidate: false
127
+ });
128
+ mutate(messagesSnapshot);
129
+ const res = yield fetch(api, {
130
+ method: "POST",
131
+ body: JSON.stringify(__spreadValues(__spreadValues({
132
+ messages: sendExtraMessageFields ? messagesSnapshot : messagesSnapshot.map(({ role, content }) => ({
133
+ role,
134
+ content
135
+ }))
136
+ }, body), options == null ? void 0 : options.body)),
137
+ headers: __spreadValues(__spreadValues({}, headers), options == null ? void 0 : options.headers),
138
+ signal: abortController.signal,
139
+ credentials
140
+ }).catch((err) => {
141
+ if (previousMessages.status === "success") {
142
+ mutate(previousMessages.data);
143
+ }
144
+ throw err;
145
+ });
146
+ if (onResponse) {
147
+ try {
148
+ yield onResponse(res);
149
+ } catch (err) {
150
+ throw err;
151
+ }
152
+ }
153
+ if (!res.ok) {
154
+ if (previousMessages.status === "success") {
155
+ mutate(previousMessages.data);
156
+ }
157
+ throw new Error(
158
+ (yield res.text()) || "Failed to fetch the chat response."
159
+ );
160
+ }
161
+ if (!res.body) {
162
+ throw new Error("The response body is empty.");
163
+ }
164
+ let result = "";
165
+ const createdAt = /* @__PURE__ */ new Date();
166
+ const replyId = nanoid();
167
+ const reader = res.body.getReader();
168
+ const decoder = createChunkDecoder();
169
+ while (true) {
170
+ const { done, value } = yield reader.read();
171
+ if (done) {
172
+ break;
173
+ }
174
+ result += decoder(value);
175
+ mutate([
176
+ ...messagesSnapshot,
177
+ {
178
+ id: replyId,
179
+ createdAt,
180
+ content: result,
181
+ role: "assistant"
182
+ }
183
+ ]);
184
+ if (abortController === null) {
185
+ reader.cancel();
186
+ break;
187
+ }
188
+ }
189
+ if (onFinish) {
190
+ onFinish({
191
+ id: replyId,
192
+ createdAt,
193
+ content: result,
194
+ role: "assistant"
195
+ });
196
+ }
197
+ abortController = null;
198
+ return result;
199
+ } catch (err) {
200
+ if (err.name === "AbortError") {
201
+ abortController = null;
202
+ return null;
203
+ }
204
+ if (onError && err instanceof Error) {
205
+ onError(err);
206
+ }
207
+ setError(err);
208
+ } finally {
209
+ setIsLoading(false);
210
+ }
211
+ });
212
+ }
213
+ const append = (message, options) => __async(this, null, function* () {
214
+ var _a;
215
+ if (!message.id) {
216
+ message.id = nanoid();
217
+ }
218
+ return triggerRequest(
219
+ ((_a = messages()) != null ? _a : []).concat(message),
220
+ options
221
+ );
222
+ });
223
+ const reload = (options) => __async(this, null, function* () {
224
+ const messagesSnapshot = messages();
225
+ if (!messagesSnapshot || messagesSnapshot.length === 0)
226
+ return null;
227
+ const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
228
+ if (lastMessage.role === "assistant") {
229
+ return triggerRequest(messagesSnapshot.slice(0, -1), options);
230
+ }
231
+ return triggerRequest(messagesSnapshot, options);
232
+ });
233
+ const stop = () => {
234
+ if (abortController) {
235
+ abortController.abort();
236
+ abortController = null;
237
+ }
238
+ };
239
+ const setMessages = (messages2) => {
240
+ mutate(messages2);
241
+ };
242
+ const [input, setInput] = (0, import_solid_js.createSignal)(initialInput);
243
+ const handleSubmit = (e) => {
244
+ e.preventDefault();
245
+ const inputValue = input();
246
+ if (!inputValue)
247
+ return;
248
+ append({
249
+ content: inputValue,
250
+ role: "user",
251
+ createdAt: /* @__PURE__ */ new Date()
252
+ });
253
+ setInput("");
254
+ };
255
+ return {
256
+ messages,
257
+ append,
258
+ error,
259
+ reload,
260
+ stop,
261
+ setMessages,
262
+ input,
263
+ setInput,
264
+ handleSubmit,
265
+ isLoading
266
+ };
267
+ }
268
+
269
+ // solid/use-completion.ts
270
+ var import_solid_js2 = require("solid-js");
271
+ var import_swr_store2 = require("swr-store");
272
+ var import_solid_swr_store2 = require("solid-swr-store");
273
+ var uniqueId2 = 0;
274
+ var store2 = {};
275
+ var completionApiStore = (0, import_swr_store2.createSWRStore)({
276
+ get: (key) => __async(void 0, null, function* () {
277
+ var _a;
278
+ return (_a = store2[key]) != null ? _a : [];
279
+ })
280
+ });
281
+ function useCompletion({
282
+ api = "/api/completion",
283
+ id,
284
+ initialCompletion = "",
285
+ initialInput = "",
286
+ credentials,
287
+ headers,
288
+ body,
289
+ onResponse,
290
+ onFinish,
291
+ onError
292
+ } = {}) {
293
+ const completionId = id || `completion-${uniqueId2++}`;
294
+ const key = `${api}|${completionId}`;
295
+ const data = (0, import_solid_swr_store2.useSWRStore)(completionApiStore, () => [key], {
296
+ initialData: initialCompletion
297
+ });
298
+ const mutate = (data2) => {
299
+ store2[key] = data2;
300
+ return completionApiStore.mutate([key], {
301
+ data: data2,
302
+ status: "success"
303
+ });
304
+ };
305
+ const completion = data;
306
+ const [error, setError] = (0, import_solid_js2.createSignal)(void 0);
307
+ const [isLoading, setIsLoading] = (0, import_solid_js2.createSignal)(false);
308
+ let abortController = null;
309
+ function triggerRequest(prompt, options) {
310
+ return __async(this, null, function* () {
311
+ try {
312
+ setIsLoading(true);
313
+ abortController = new AbortController();
314
+ mutate("");
315
+ const res = yield fetch(api, {
316
+ method: "POST",
317
+ body: JSON.stringify(__spreadValues(__spreadValues({
318
+ prompt
319
+ }, body), options == null ? void 0 : options.body)),
320
+ headers: __spreadValues(__spreadValues({}, headers), options == null ? void 0 : options.headers),
321
+ signal: abortController.signal,
322
+ credentials
323
+ }).catch((err) => {
324
+ throw err;
325
+ });
326
+ if (onResponse) {
327
+ try {
328
+ yield onResponse(res);
329
+ } catch (err) {
330
+ throw err;
331
+ }
332
+ }
333
+ if (!res.ok) {
334
+ throw new Error(
335
+ (yield res.text()) || "Failed to fetch the chat response."
336
+ );
337
+ }
338
+ if (!res.body) {
339
+ throw new Error("The response body is empty.");
340
+ }
341
+ let result = "";
342
+ const reader = res.body.getReader();
343
+ const decoder = createChunkDecoder();
344
+ while (true) {
345
+ const { done, value } = yield reader.read();
346
+ if (done) {
347
+ break;
348
+ }
349
+ result += decoder(value);
350
+ mutate(result);
351
+ if (abortController === null) {
352
+ reader.cancel();
353
+ break;
354
+ }
355
+ }
356
+ if (onFinish) {
357
+ onFinish(prompt, result);
358
+ }
359
+ abortController = null;
360
+ return result;
361
+ } catch (err) {
362
+ if (err.name === "AbortError") {
363
+ abortController = null;
364
+ return null;
365
+ }
366
+ if (onError && error instanceof Error) {
367
+ onError(error);
368
+ }
369
+ setError(err);
370
+ } finally {
371
+ setIsLoading(false);
372
+ }
373
+ });
374
+ }
375
+ const complete = (prompt, options) => __async(this, null, function* () {
376
+ return triggerRequest(prompt, options);
377
+ });
378
+ const stop = () => {
379
+ if (abortController) {
380
+ abortController.abort();
381
+ abortController = null;
382
+ }
383
+ };
384
+ const setCompletion = (completion2) => {
385
+ mutate(completion2);
386
+ };
387
+ const [input, setInput] = (0, import_solid_js2.createSignal)(initialInput);
388
+ const handleSubmit = (e) => {
389
+ e.preventDefault();
390
+ const inputValue = input();
391
+ if (!inputValue)
392
+ return;
393
+ return complete(inputValue);
394
+ };
395
+ return {
396
+ completion,
397
+ complete,
398
+ error,
399
+ stop,
400
+ setCompletion,
401
+ input,
402
+ setInput,
403
+ handleSubmit,
404
+ isLoading
405
+ };
406
+ }
407
+ // Annotate the CommonJS export names for ESM import in node:
408
+ 0 && (module.exports = {
409
+ useChat,
410
+ useCompletion
411
+ });