ai 2.1.27 → 2.1.29

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/README.md CHANGED
@@ -5,7 +5,7 @@ The Vercel AI SDK is **a library for building AI-powered streaming text and chat
5
5
  ## Features
6
6
 
7
7
  - [SWR](https://swr.vercel.app)-powered React, Svelte, Vue and Solid helpers for streaming text responses and building chat and completion UIs
8
- - First-class support for [LangChain](js.langchain.com/docs) and [OpenAI](https://openai.com), [Anthropic](https://www.anthropic.com), [Cohere](https://cohere.com) and [Hugging Face](https://huggingface.co)
8
+ - First-class support for [LangChain](https://js.langchain.com/docs) and [OpenAI](https://openai.com), [Anthropic](https://www.anthropic.com), [Cohere](https://cohere.com) and [Hugging Face](https://huggingface.co)
9
9
  - Node.js, Serverless, and [Edge Runtime](https://edge-runtime.vercel.app/) support
10
10
  - Callbacks for saving completed streaming responses to a database (in the same request)
11
11
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { ChatCompletionRequestMessageFunctionCall, CreateChatCompletionRequestFunctionCall } from 'openai-edge';
2
2
  import { ChatCompletionFunctions } from 'openai-edge/types/api';
3
3
  import { ServerResponse } from 'node:http';
4
+ import { Prediction } from 'replicate';
4
5
 
5
6
  interface FunctionCallPayload {
6
7
  name: string;
@@ -27,7 +28,7 @@ interface AIStreamParser {
27
28
  * @param {AIStreamParser} customParser - Function to handle event data.
28
29
  * @returns {TransformStream<Uint8Array, string>} TransformStream parsing events.
29
30
  */
30
- declare function createEventStreamTransformer(customParser: AIStreamParser): TransformStream<Uint8Array, string>;
31
+ declare function createEventStreamTransformer(customParser?: AIStreamParser): TransformStream<Uint8Array, string>;
31
32
  /**
32
33
  * Creates a transform stream that encodes input messages and invokes optional callback functions.
33
34
  * The transform stream uses the provided callbacks to execute custom logic at different stages of the stream's lifecycle.
@@ -83,7 +84,7 @@ declare function trimStartOfStreamHelper(): (text: string) => string;
83
84
  * @return {ReadableStream} The AIStream.
84
85
  * @throws Will throw an error if the response is not OK.
85
86
  */
86
- declare function AIStream(response: Response, customParser: AIStreamParser, callbacks?: AIStreamCallbacks): ReadableStream<Uint8Array>;
87
+ declare function AIStream(response: Response, customParser?: AIStreamParser, callbacks?: AIStreamCallbacks): ReadableStream<Uint8Array>;
87
88
  /**
88
89
  * Implements ReadableStream.from(asyncIterable), which isn't documented in MDN and isn't implemented in node.
89
90
  * https://github.com/whatwg/streams/commit/8d7a0bf26eb2cc23e884ddbaac7c1da4b91cf2bc
@@ -365,7 +366,28 @@ declare function LangChainStream(callbacks?: AIStreamCallbacks): {
365
366
  };
366
367
  };
367
368
 
369
+ /**
370
+ * Stream predictions from Replicate.
371
+ * Only certain models are supported and you must pass `stream: true` to
372
+ * replicate.predictions.create().
373
+ * @see https://github.com/replicate/replicate-javascript#streaming
374
+ *
375
+ * @example
376
+ * const response = await replicate.predictions.create({
377
+ * stream: true,
378
+ * input: {
379
+ * prompt: messages.join('\n')
380
+ * },
381
+ * version: '2c1608e18606fad2812020dc541930f2d0495ce32eee50074220b87300bc16e1'
382
+ * })
383
+ *
384
+ * const stream = await ReplicateStream(response)
385
+ * return new StreamingTextResponse(stream)
386
+ *
387
+ */
388
+ declare function ReplicateStream(res: Prediction, cb?: AIStreamCallbacks): Promise<ReadableStream>;
389
+
368
390
  declare const nanoid: (size?: number | undefined) => string;
369
391
  declare function createChunkDecoder(): (chunk: Uint8Array | undefined) => string;
370
392
 
371
- export { AIStream, AIStreamCallbacks, AIStreamParser, AnthropicStream, ChatRequest, ChatRequestOptions, CohereStream, CreateMessage, FunctionCallHandler, FunctionCallPayload, HuggingFaceStream, LangChainStream, Message, OpenAIStream, OpenAIStreamCallbacks, RequestOptions, StreamingTextResponse, UseChatOptions, UseCompletionOptions, createCallbacksTransformer, createChunkDecoder, createEventStreamTransformer, nanoid, readableFromAsyncIterable, streamToResponse, trimStartOfStreamHelper };
393
+ export { AIStream, AIStreamCallbacks, AIStreamParser, AnthropicStream, ChatRequest, ChatRequestOptions, CohereStream, CreateMessage, FunctionCallHandler, FunctionCallPayload, HuggingFaceStream, LangChainStream, Message, OpenAIStream, OpenAIStreamCallbacks, ReplicateStream, RequestOptions, StreamingTextResponse, UseChatOptions, UseCompletionOptions, createCallbacksTransformer, createChunkDecoder, createEventStreamTransformer, nanoid, readableFromAsyncIterable, streamToResponse, trimStartOfStreamHelper };
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ __export(streams_exports, {
26
26
  HuggingFaceStream: () => HuggingFaceStream,
27
27
  LangChainStream: () => LangChainStream,
28
28
  OpenAIStream: () => OpenAIStream,
29
+ ReplicateStream: () => ReplicateStream,
29
30
  StreamingTextResponse: () => StreamingTextResponse,
30
31
  createCallbacksTransformer: () => createCallbacksTransformer,
31
32
  createChunkDecoder: () => createChunkDecoder,
@@ -51,7 +52,7 @@ function createEventStreamTransformer(customParser) {
51
52
  return;
52
53
  }
53
54
  if ("data" in event) {
54
- const parsedMessage = customParser(event.data);
55
+ const parsedMessage = customParser ? customParser(event.data) : event.data;
55
56
  if (parsedMessage)
56
57
  controller.enqueue(parsedMessage);
57
58
  }
@@ -462,6 +463,25 @@ function LangChainStream(callbacks) {
462
463
  };
463
464
  }
464
465
 
466
+ // streams/replicate-stream.ts
467
+ async function ReplicateStream(res, cb) {
468
+ var _a;
469
+ const url = (_a = res.urls) == null ? void 0 : _a.stream;
470
+ if (!url) {
471
+ if (res.error)
472
+ throw new Error(res.error);
473
+ else
474
+ throw new Error("Missing stream URL in Replicate response");
475
+ }
476
+ const eventStream = await fetch(url, {
477
+ method: "GET",
478
+ headers: {
479
+ Accept: "text/event-stream"
480
+ }
481
+ });
482
+ return AIStream(eventStream, void 0, cb);
483
+ }
484
+
465
485
  // shared/utils.ts
466
486
  var import_non_secure = require("nanoid/non-secure");
467
487
  var nanoid = (0, import_non_secure.customAlphabet)(
@@ -484,6 +504,7 @@ function createChunkDecoder() {
484
504
  HuggingFaceStream,
485
505
  LangChainStream,
486
506
  OpenAIStream,
507
+ ReplicateStream,
487
508
  StreamingTextResponse,
488
509
  createCallbacksTransformer,
489
510
  createChunkDecoder,
package/dist/index.mjs CHANGED
@@ -14,7 +14,7 @@ function createEventStreamTransformer(customParser) {
14
14
  return;
15
15
  }
16
16
  if ("data" in event) {
17
- const parsedMessage = customParser(event.data);
17
+ const parsedMessage = customParser ? customParser(event.data) : event.data;
18
18
  if (parsedMessage)
19
19
  controller.enqueue(parsedMessage);
20
20
  }
@@ -425,6 +425,25 @@ function LangChainStream(callbacks) {
425
425
  };
426
426
  }
427
427
 
428
+ // streams/replicate-stream.ts
429
+ async function ReplicateStream(res, cb) {
430
+ var _a;
431
+ const url = (_a = res.urls) == null ? void 0 : _a.stream;
432
+ if (!url) {
433
+ if (res.error)
434
+ throw new Error(res.error);
435
+ else
436
+ throw new Error("Missing stream URL in Replicate response");
437
+ }
438
+ const eventStream = await fetch(url, {
439
+ method: "GET",
440
+ headers: {
441
+ Accept: "text/event-stream"
442
+ }
443
+ });
444
+ return AIStream(eventStream, void 0, cb);
445
+ }
446
+
428
447
  // shared/utils.ts
429
448
  import { customAlphabet } from "nanoid/non-secure";
430
449
  var nanoid = customAlphabet(
@@ -446,6 +465,7 @@ export {
446
465
  HuggingFaceStream,
447
466
  LangChainStream,
448
467
  OpenAIStream,
468
+ ReplicateStream,
449
469
  StreamingTextResponse,
450
470
  createCallbacksTransformer,
451
471
  createChunkDecoder,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "2.1.27",
3
+ "version": "2.1.29",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -61,11 +61,11 @@
61
61
  "dependencies": {
62
62
  "eventsource-parser": "1.0.0",
63
63
  "nanoid": "3.3.6",
64
+ "solid-swr-store": "0.10.7",
64
65
  "sswr": "2.0.0",
65
66
  "swr": "2.2.0",
66
- "swrv": "1.0.4",
67
- "solid-swr-store": "0.10.7",
68
- "swr-store": "0.10.6"
67
+ "swr-store": "0.10.6",
68
+ "swrv": "1.0.4"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@edge-runtime/jest-environment": "1.1.0-beta.31",
@@ -76,11 +76,12 @@
76
76
  "eslint": "^7.32.0",
77
77
  "jest": "29.2.1",
78
78
  "openai-edge": "^1.1.0",
79
+ "replicate": "^0.14.1",
79
80
  "ts-jest": "29.0.3",
80
81
  "tsup": "^6.7.0",
81
82
  "typescript": "5.1.3",
82
- "@vercel/ai-tsconfig": "0.0.0",
83
- "eslint-config-vercel-ai": "0.0.0"
83
+ "eslint-config-vercel-ai": "0.0.0",
84
+ "@vercel/ai-tsconfig": "0.0.0"
84
85
  },
85
86
  "peerDependencies": {
86
87
  "react": "^18.2.0",
@@ -166,7 +166,7 @@ function useChat({
166
166
  fallbackData: initialMessages
167
167
  });
168
168
  const { data: isLoading = false, mutate: mutateLoading } = (0, import_swr.default)(
169
- [api, chatId, "loading"],
169
+ [chatId, "loading"],
170
170
  null
171
171
  );
172
172
  const messages = data;
@@ -346,7 +346,7 @@ function useCompletion({
346
346
  fallbackData: initialCompletion
347
347
  });
348
348
  const { data: isLoading = false, mutate: mutateLoading } = (0, import_swr2.default)(
349
- [api, completionId, "loading"],
349
+ [completionId, "loading"],
350
350
  null
351
351
  );
352
352
  const [error, setError] = (0, import_react2.useState)(void 0);
@@ -130,7 +130,7 @@ function useChat({
130
130
  fallbackData: initialMessages
131
131
  });
132
132
  const { data: isLoading = false, mutate: mutateLoading } = useSWR(
133
- [api, chatId, "loading"],
133
+ [chatId, "loading"],
134
134
  null
135
135
  );
136
136
  const messages = data;
@@ -310,7 +310,7 @@ function useCompletion({
310
310
  fallbackData: initialCompletion
311
311
  });
312
312
  const { data: isLoading = false, mutate: mutateLoading } = useSWR2(
313
- [api, completionId, "loading"],
313
+ [completionId, "loading"],
314
314
  null
315
315
  );
316
316
  const [error, setError] = useState2(void 0);
@@ -200,7 +200,7 @@ type UseChatHelpers = {
200
200
  handleSubmit: (e: any, chatRequestOptions?: ChatRequestOptions) => void;
201
201
  metadata?: Object;
202
202
  /** Whether the API request is in progress */
203
- isLoading: Writable<boolean | undefined>;
203
+ isLoading: Readable<boolean | undefined>;
204
204
  };
205
205
  declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, onResponse, onFinish, onError, credentials, headers, body }?: UseChatOptions): UseChatHelpers;
206
206
 
@@ -234,7 +234,7 @@ type UseCompletionHelpers = {
234
234
  */
235
235
  handleSubmit: (e: any) => void;
236
236
  /** Whether the API request is in progress */
237
- isLoading: Writable<boolean | undefined>;
237
+ isLoading: Readable<boolean | undefined>;
238
238
  };
239
239
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, onResponse, onFinish, onError }?: UseCompletionOptions): UseCompletionHelpers;
240
240
 
@@ -653,13 +653,15 @@ function useChat({
653
653
  } = {}) {
654
654
  const chatId = id || `chat-${uniqueId++}`;
655
655
  const key = `${api}|${chatId}`;
656
- const { data, mutate: originalMutate } = F2(key, {
656
+ const {
657
+ data,
658
+ mutate: originalMutate,
659
+ isLoading: isSWRLoading
660
+ } = F2(key, {
657
661
  fetcher: () => store[key] || initialMessages,
658
662
  fallbackData: initialMessages
659
663
  });
660
- const { data: isLoading, mutate: mutateLoading } = F2(
661
- `${key}-loading`
662
- );
664
+ const loading = (0, import_store.writable)(false);
663
665
  data.set(initialMessages);
664
666
  const mutate = (data2) => {
665
667
  store[key] = data2;
@@ -675,7 +677,7 @@ function useChat({
675
677
  const error = (0, import_store.writable)(void 0);
676
678
  async function triggerRequest(chatRequest) {
677
679
  try {
678
- mutateLoading(true);
680
+ loading.set(true);
679
681
  abortController = new AbortController();
680
682
  while (true) {
681
683
  const streamedResponseMessage = await getStreamedResponse(
@@ -712,7 +714,7 @@ function useChat({
712
714
  }
713
715
  error.set(err);
714
716
  } finally {
715
- mutateLoading(false);
717
+ loading.set(false);
716
718
  }
717
719
  }
718
720
  const append = async (message, { options, functions, function_call } = {}) => {
@@ -787,7 +789,7 @@ function useChat({
787
789
  setMessages,
788
790
  input,
789
791
  handleSubmit,
790
- isLoading
792
+ isLoading: isSWRLoading || loading
791
793
  };
792
794
  }
793
795
 
@@ -817,9 +819,7 @@ function useCompletion({
817
819
  fetcher: () => store2[key] || initialCompletion,
818
820
  fallbackData: initialCompletion
819
821
  });
820
- const { data: isLoading, mutate: mutateLoading } = F2(
821
- `${key}-loading`
822
- );
822
+ const loading = (0, import_store2.writable)(false);
823
823
  data.set(initialCompletion);
824
824
  const mutate = (data2) => {
825
825
  store2[key] = data2;
@@ -830,7 +830,7 @@ function useCompletion({
830
830
  let abortController = null;
831
831
  async function triggerRequest(prompt, options) {
832
832
  try {
833
- mutateLoading(true);
833
+ loading.set(true);
834
834
  abortController = new AbortController();
835
835
  mutate("");
836
836
  const res = await fetch(api, {
@@ -894,7 +894,7 @@ function useCompletion({
894
894
  }
895
895
  error.set(err);
896
896
  } finally {
897
- mutateLoading(false);
897
+ loading.set(false);
898
898
  }
899
899
  }
900
900
  const complete = async (prompt, options) => {
@@ -925,7 +925,7 @@ function useCompletion({
925
925
  setCompletion,
926
926
  input,
927
927
  handleSubmit,
928
- isLoading
928
+ isLoading: isSWRLoading || loading
929
929
  };
930
930
  }
931
931
  // Annotate the CommonJS export names for ESM import in node:
@@ -626,13 +626,15 @@ function useChat({
626
626
  } = {}) {
627
627
  const chatId = id || `chat-${uniqueId++}`;
628
628
  const key = `${api}|${chatId}`;
629
- const { data, mutate: originalMutate } = F2(key, {
629
+ const {
630
+ data,
631
+ mutate: originalMutate,
632
+ isLoading: isSWRLoading
633
+ } = F2(key, {
630
634
  fetcher: () => store[key] || initialMessages,
631
635
  fallbackData: initialMessages
632
636
  });
633
- const { data: isLoading, mutate: mutateLoading } = F2(
634
- `${key}-loading`
635
- );
637
+ const loading = writable(false);
636
638
  data.set(initialMessages);
637
639
  const mutate = (data2) => {
638
640
  store[key] = data2;
@@ -648,7 +650,7 @@ function useChat({
648
650
  const error = writable(void 0);
649
651
  async function triggerRequest(chatRequest) {
650
652
  try {
651
- mutateLoading(true);
653
+ loading.set(true);
652
654
  abortController = new AbortController();
653
655
  while (true) {
654
656
  const streamedResponseMessage = await getStreamedResponse(
@@ -685,7 +687,7 @@ function useChat({
685
687
  }
686
688
  error.set(err);
687
689
  } finally {
688
- mutateLoading(false);
690
+ loading.set(false);
689
691
  }
690
692
  }
691
693
  const append = async (message, { options, functions, function_call } = {}) => {
@@ -760,7 +762,7 @@ function useChat({
760
762
  setMessages,
761
763
  input,
762
764
  handleSubmit,
763
- isLoading
765
+ isLoading: isSWRLoading || loading
764
766
  };
765
767
  }
766
768
 
@@ -790,9 +792,7 @@ function useCompletion({
790
792
  fetcher: () => store2[key] || initialCompletion,
791
793
  fallbackData: initialCompletion
792
794
  });
793
- const { data: isLoading, mutate: mutateLoading } = F2(
794
- `${key}-loading`
795
- );
795
+ const loading = writable2(false);
796
796
  data.set(initialCompletion);
797
797
  const mutate = (data2) => {
798
798
  store2[key] = data2;
@@ -803,7 +803,7 @@ function useCompletion({
803
803
  let abortController = null;
804
804
  async function triggerRequest(prompt, options) {
805
805
  try {
806
- mutateLoading(true);
806
+ loading.set(true);
807
807
  abortController = new AbortController();
808
808
  mutate("");
809
809
  const res = await fetch(api, {
@@ -867,7 +867,7 @@ function useCompletion({
867
867
  }
868
868
  error.set(err);
869
869
  } finally {
870
- mutateLoading(false);
870
+ loading.set(false);
871
871
  }
872
872
  }
873
873
  const complete = async (prompt, options) => {
@@ -898,7 +898,7 @@ function useCompletion({
898
898
  setCompletion,
899
899
  input,
900
900
  handleSubmit,
901
- isLoading
901
+ isLoading: isSWRLoading || loading
902
902
  };
903
903
  }
904
904
  export {
package/vue/dist/index.js CHANGED
@@ -78,7 +78,7 @@ function useChat({
78
78
  () => store[key] || initialMessages
79
79
  );
80
80
  const { data: isLoading, mutate: mutateLoading } = useSWRV(
81
- `${key}-loading`
81
+ `${chatId}-loading`
82
82
  );
83
83
  data.value || (data.value = initialMessages);
84
84
  const mutate = (data2) => {
@@ -253,7 +253,7 @@ function useCompletion({
253
253
  () => store2[key] || initialCompletion
254
254
  );
255
255
  const { data: isLoading, mutate: mutateLoading } = useSWRV2(
256
- `${key}-loading`
256
+ `${completionId}-loading`
257
257
  );
258
258
  data.value || (data.value = initialCompletion);
259
259
  const mutate = (data2) => {
@@ -41,7 +41,7 @@ function useChat({
41
41
  () => store[key] || initialMessages
42
42
  );
43
43
  const { data: isLoading, mutate: mutateLoading } = useSWRV(
44
- `${key}-loading`
44
+ `${chatId}-loading`
45
45
  );
46
46
  data.value || (data.value = initialMessages);
47
47
  const mutate = (data2) => {
@@ -216,7 +216,7 @@ function useCompletion({
216
216
  () => store2[key] || initialCompletion
217
217
  );
218
218
  const { data: isLoading, mutate: mutateLoading } = useSWRV2(
219
- `${key}-loading`
219
+ `${completionId}-loading`
220
220
  );
221
221
  data.value || (data.value = initialCompletion);
222
222
  const mutate = (data2) => {