ai 2.2.1 → 2.2.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.
- package/dist/index.d.ts +214 -101
- package/dist/index.js +290 -92
- package/dist/index.mjs +283 -92
- package/package.json +1 -1
- package/react/dist/index.d.ts +2 -0
- package/react/dist/index.js +194 -52
- package/react/dist/index.mjs +194 -52
- package/solid/dist/index.js +34 -4
- package/solid/dist/index.mjs +34 -4
- package/svelte/dist/index.js +34 -4
- package/svelte/dist/index.mjs +34 -4
- package/vue/dist/index.js +34 -4
- package/vue/dist/index.mjs +34 -4
package/dist/index.d.ts
CHANGED
@@ -2,94 +2,6 @@ import { ChatCompletionMessage, CompletionCreateParams, CreateChatCompletionRequ
|
|
2
2
|
import { ServerResponse } from 'node:http';
|
3
3
|
import { Prediction } from 'replicate';
|
4
4
|
|
5
|
-
interface FunctionCallPayload {
|
6
|
-
name: string;
|
7
|
-
arguments: Record<string, unknown>;
|
8
|
-
}
|
9
|
-
/**
|
10
|
-
* Helper callback methods for AIStream stream lifecycle events
|
11
|
-
* @interface
|
12
|
-
*/
|
13
|
-
interface AIStreamCallbacks {
|
14
|
-
onStart?: () => Promise<void> | void;
|
15
|
-
onCompletion?: (completion: string) => Promise<void> | void;
|
16
|
-
onToken?: (token: string) => Promise<void> | void;
|
17
|
-
}
|
18
|
-
/**
|
19
|
-
* Custom parser for AIStream data.
|
20
|
-
* @interface
|
21
|
-
*/
|
22
|
-
interface AIStreamParser {
|
23
|
-
(data: string): string | void;
|
24
|
-
}
|
25
|
-
/**
|
26
|
-
* Creates a TransformStream that parses events from an EventSource stream using a custom parser.
|
27
|
-
* @param {AIStreamParser} customParser - Function to handle event data.
|
28
|
-
* @returns {TransformStream<Uint8Array, string>} TransformStream parsing events.
|
29
|
-
*/
|
30
|
-
declare function createEventStreamTransformer(customParser?: AIStreamParser): TransformStream<Uint8Array, string>;
|
31
|
-
/**
|
32
|
-
* Creates a transform stream that encodes input messages and invokes optional callback functions.
|
33
|
-
* The transform stream uses the provided callbacks to execute custom logic at different stages of the stream's lifecycle.
|
34
|
-
* - `onStart`: Called once when the stream is initialized.
|
35
|
-
* - `onToken`: Called for each tokenized message.
|
36
|
-
* - `onCompletion`: Called once when the stream is flushed, with the aggregated messages.
|
37
|
-
*
|
38
|
-
* This function is useful when you want to process a stream of messages and perform specific actions during the stream's lifecycle.
|
39
|
-
*
|
40
|
-
* @param {AIStreamCallbacks} [callbacks] - An object containing the callback functions.
|
41
|
-
* @return {TransformStream<string, Uint8Array>} A transform stream that encodes input messages as Uint8Array and allows the execution of custom logic through callbacks.
|
42
|
-
*
|
43
|
-
* @example
|
44
|
-
* const callbacks = {
|
45
|
-
* onStart: async () => console.log('Stream started'),
|
46
|
-
* onToken: async (token) => console.log(`Token: ${token}`),
|
47
|
-
* onCompletion: async (completion) => console.log(`Completion: ${completion}`)
|
48
|
-
* };
|
49
|
-
* const transformer = createCallbacksTransformer(callbacks);
|
50
|
-
*/
|
51
|
-
declare function createCallbacksTransformer(callbacks: AIStreamCallbacks | undefined): TransformStream<string, Uint8Array>;
|
52
|
-
/**
|
53
|
-
* Returns a stateful function that, when invoked, trims leading whitespace
|
54
|
-
* from the input text. The trimming only occurs on the first invocation, ensuring that
|
55
|
-
* subsequent calls do not alter the input text. This is particularly useful in scenarios
|
56
|
-
* where a text stream is being processed and only the initial whitespace should be removed.
|
57
|
-
*
|
58
|
-
* @return {function(string): string} A function that takes a string as input and returns a string
|
59
|
-
* with leading whitespace removed if it is the first invocation; otherwise, it returns the input unchanged.
|
60
|
-
*
|
61
|
-
* @example
|
62
|
-
* const trimStart = trimStartOfStreamHelper();
|
63
|
-
* const output1 = trimStart(" text"); // "text"
|
64
|
-
* const output2 = trimStart(" text"); // " text"
|
65
|
-
*
|
66
|
-
*/
|
67
|
-
declare function trimStartOfStreamHelper(): (text: string) => string;
|
68
|
-
/**
|
69
|
-
* Returns a ReadableStream created from the response, parsed and handled with custom logic.
|
70
|
-
* The stream goes through two transformation stages, first parsing the events and then
|
71
|
-
* invoking the provided callbacks.
|
72
|
-
*
|
73
|
-
* For 2xx HTTP responses:
|
74
|
-
* - The function continues with standard stream processing.
|
75
|
-
*
|
76
|
-
* For non-2xx HTTP responses:
|
77
|
-
* - If the response body is defined, it asynchronously extracts and decodes the response body.
|
78
|
-
* - It then creates a custom ReadableStream to propagate a detailed error message.
|
79
|
-
*
|
80
|
-
* @param {Response} response - The response.
|
81
|
-
* @param {AIStreamParser} customParser - The custom parser function.
|
82
|
-
* @param {AIStreamCallbacks} callbacks - The callbacks.
|
83
|
-
* @return {ReadableStream} The AIStream.
|
84
|
-
* @throws Will throw an error if the response is not OK.
|
85
|
-
*/
|
86
|
-
declare function AIStream(response: Response, customParser?: AIStreamParser, callbacks?: AIStreamCallbacks): ReadableStream<Uint8Array>;
|
87
|
-
/**
|
88
|
-
* Implements ReadableStream.from(asyncIterable), which isn't documented in MDN and isn't implemented in node.
|
89
|
-
* https://github.com/whatwg/streams/commit/8d7a0bf26eb2cc23e884ddbaac7c1da4b91cf2bc
|
90
|
-
*/
|
91
|
-
declare function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>): ReadableStream<T>;
|
92
|
-
|
93
5
|
/**
|
94
6
|
* Shared types between the API and UI packages.
|
95
7
|
*/
|
@@ -253,11 +165,11 @@ type UseCompletionOptions = {
|
|
253
165
|
*/
|
254
166
|
body?: object;
|
255
167
|
};
|
256
|
-
|
257
168
|
type JSONValue = null | string | number | boolean | {
|
258
169
|
[x: string]: JSONValue;
|
259
170
|
} | Array<JSONValue>;
|
260
|
-
|
171
|
+
|
172
|
+
type OpenAIStreamCallbacks = AIStreamCallbacksAndOptions & {
|
261
173
|
/**
|
262
174
|
* @example
|
263
175
|
* ```js
|
@@ -285,7 +197,7 @@ type OpenAIStreamCallbacks = AIStreamCallbacks & {
|
|
285
197
|
* })
|
286
198
|
* ```
|
287
199
|
*/
|
288
|
-
experimental_onFunctionCall?: (functionCallPayload: FunctionCallPayload, createFunctionCallMessages: (functionCallResult: JSONValue) => CreateMessage[]) => Promise<Response | undefined | void | string |
|
200
|
+
experimental_onFunctionCall?: (functionCallPayload: FunctionCallPayload, createFunctionCallMessages: (functionCallResult: JSONValue) => CreateMessage[]) => Promise<Response | undefined | void | string | AsyncIterableOpenAIStreamReturnTypes>;
|
289
201
|
};
|
290
202
|
interface ChatCompletionChunk {
|
291
203
|
id: string;
|
@@ -327,13 +239,174 @@ interface FunctionCall {
|
|
327
239
|
*/
|
328
240
|
name?: string;
|
329
241
|
}
|
330
|
-
|
242
|
+
/**
|
243
|
+
* https://github.com/openai/openai-node/blob/3ec43ee790a2eb6a0ccdd5f25faa23251b0f9b8e/src/resources/completions.ts#L28C1-L64C1
|
244
|
+
* Completions API. Streamed and non-streamed responses are the same.
|
245
|
+
*/
|
246
|
+
interface Completion {
|
247
|
+
/**
|
248
|
+
* A unique identifier for the completion.
|
249
|
+
*/
|
250
|
+
id: string;
|
251
|
+
/**
|
252
|
+
* The list of completion choices the model generated for the input prompt.
|
253
|
+
*/
|
254
|
+
choices: Array<CompletionChoice>;
|
255
|
+
/**
|
256
|
+
* The Unix timestamp of when the completion was created.
|
257
|
+
*/
|
258
|
+
created: number;
|
259
|
+
/**
|
260
|
+
* The model used for completion.
|
261
|
+
*/
|
262
|
+
model: string;
|
263
|
+
/**
|
264
|
+
* The object type, which is always "text_completion"
|
265
|
+
*/
|
266
|
+
object: string;
|
267
|
+
}
|
268
|
+
interface CompletionChoice {
|
269
|
+
/**
|
270
|
+
* The reason the model stopped generating tokens. This will be `stop` if the model
|
271
|
+
* hit a natural stop point or a provided stop sequence, or `length` if the maximum
|
272
|
+
* number of tokens specified in the request was reached.
|
273
|
+
*/
|
274
|
+
finish_reason: 'stop' | 'length';
|
275
|
+
index: number;
|
276
|
+
logprobs: any | null;
|
277
|
+
text: string;
|
278
|
+
}
|
279
|
+
type AsyncIterableOpenAIStreamReturnTypes = AsyncIterable<ChatCompletionChunk> | AsyncIterable<Completion>;
|
280
|
+
declare function OpenAIStream(res: Response | AsyncIterableOpenAIStreamReturnTypes, callbacks?: OpenAIStreamCallbacks): ReadableStream;
|
281
|
+
|
282
|
+
interface FunctionCallPayload {
|
283
|
+
name: string;
|
284
|
+
arguments: Record<string, unknown>;
|
285
|
+
}
|
286
|
+
/**
|
287
|
+
* Configuration options and helper callback methods for AIStream stream lifecycle events.
|
288
|
+
* @interface
|
289
|
+
*/
|
290
|
+
interface AIStreamCallbacksAndOptions {
|
291
|
+
/** `onStart`: Called once when the stream is initialized. */
|
292
|
+
onStart?: () => Promise<void> | void;
|
293
|
+
/** `onCompletion`: Called for each tokenized message. */
|
294
|
+
onCompletion?: (completion: string) => Promise<void> | void;
|
295
|
+
/** `onFinal`: Called once when the stream is closed with the final completion message. */
|
296
|
+
onFinal?: (completion: string) => Promise<void> | void;
|
297
|
+
/** `onToken`: Called for each tokenized message. */
|
298
|
+
onToken?: (token: string) => Promise<void> | void;
|
299
|
+
/**
|
300
|
+
* A flag for enabling the experimental_StreamData class and the new protocol.
|
301
|
+
* @see https://github.com/vercel-labs/ai/pull/425
|
302
|
+
*
|
303
|
+
* When StreamData is rolled out, this will be removed and the new protocol will be used by default.
|
304
|
+
*/
|
305
|
+
experimental_streamData?: boolean;
|
306
|
+
}
|
307
|
+
/**
|
308
|
+
* Custom parser for AIStream data.
|
309
|
+
* @interface
|
310
|
+
*/
|
311
|
+
interface AIStreamParser {
|
312
|
+
(data: string): string | void;
|
313
|
+
}
|
314
|
+
/**
|
315
|
+
* Creates a TransformStream that parses events from an EventSource stream using a custom parser.
|
316
|
+
* @param {AIStreamParser} customParser - Function to handle event data.
|
317
|
+
* @returns {TransformStream<Uint8Array, string>} TransformStream parsing events.
|
318
|
+
*/
|
319
|
+
declare function createEventStreamTransformer(customParser?: AIStreamParser): TransformStream<Uint8Array, string>;
|
320
|
+
/**
|
321
|
+
* Creates a transform stream that encodes input messages and invokes optional callback functions.
|
322
|
+
* The transform stream uses the provided callbacks to execute custom logic at different stages of the stream's lifecycle.
|
323
|
+
* - `onStart`: Called once when the stream is initialized.
|
324
|
+
* - `onToken`: Called for each tokenized message.
|
325
|
+
* - `onCompletion`: Called every time an AIStream completion message is received. This can occur multiple times when using e.g. OpenAI functions
|
326
|
+
* - `onFinal`: Called once when the stream is closed with the final completion message.
|
327
|
+
*
|
328
|
+
* This function is useful when you want to process a stream of messages and perform specific actions during the stream's lifecycle.
|
329
|
+
*
|
330
|
+
* @param {AIStreamCallbacksAndOptions} [callbacks] - An object containing the callback functions.
|
331
|
+
* @return {TransformStream<string, Uint8Array>} A transform stream that encodes input messages as Uint8Array and allows the execution of custom logic through callbacks.
|
332
|
+
*
|
333
|
+
* @example
|
334
|
+
* const callbacks = {
|
335
|
+
* onStart: async () => console.log('Stream started'),
|
336
|
+
* onToken: async (token) => console.log(`Token: ${token}`),
|
337
|
+
* onCompletion: async (completion) => console.log(`Completion: ${completion}`)
|
338
|
+
* onFinal: async () => data.close()
|
339
|
+
* };
|
340
|
+
* const transformer = createCallbacksTransformer(callbacks);
|
341
|
+
*/
|
342
|
+
declare function createCallbacksTransformer(cb: AIStreamCallbacksAndOptions | OpenAIStreamCallbacks | undefined): TransformStream<string, Uint8Array>;
|
343
|
+
/**
|
344
|
+
* Returns a stateful function that, when invoked, trims leading whitespace
|
345
|
+
* from the input text. The trimming only occurs on the first invocation, ensuring that
|
346
|
+
* subsequent calls do not alter the input text. This is particularly useful in scenarios
|
347
|
+
* where a text stream is being processed and only the initial whitespace should be removed.
|
348
|
+
*
|
349
|
+
* @return {function(string): string} A function that takes a string as input and returns a string
|
350
|
+
* with leading whitespace removed if it is the first invocation; otherwise, it returns the input unchanged.
|
351
|
+
*
|
352
|
+
* @example
|
353
|
+
* const trimStart = trimStartOfStreamHelper();
|
354
|
+
* const output1 = trimStart(" text"); // "text"
|
355
|
+
* const output2 = trimStart(" text"); // " text"
|
356
|
+
*
|
357
|
+
*/
|
358
|
+
declare function trimStartOfStreamHelper(): (text: string) => string;
|
359
|
+
/**
|
360
|
+
* Returns a ReadableStream created from the response, parsed and handled with custom logic.
|
361
|
+
* The stream goes through two transformation stages, first parsing the events and then
|
362
|
+
* invoking the provided callbacks.
|
363
|
+
*
|
364
|
+
* For 2xx HTTP responses:
|
365
|
+
* - The function continues with standard stream processing.
|
366
|
+
*
|
367
|
+
* For non-2xx HTTP responses:
|
368
|
+
* - If the response body is defined, it asynchronously extracts and decodes the response body.
|
369
|
+
* - It then creates a custom ReadableStream to propagate a detailed error message.
|
370
|
+
*
|
371
|
+
* @param {Response} response - The response.
|
372
|
+
* @param {AIStreamParser} customParser - The custom parser function.
|
373
|
+
* @param {AIStreamCallbacksAndOptions} callbacks - The callbacks.
|
374
|
+
* @return {ReadableStream} The AIStream.
|
375
|
+
* @throws Will throw an error if the response is not OK.
|
376
|
+
*/
|
377
|
+
declare function AIStream(response: Response, customParser?: AIStreamParser, callbacks?: AIStreamCallbacksAndOptions): ReadableStream<Uint8Array>;
|
378
|
+
/**
|
379
|
+
* Implements ReadableStream.from(asyncIterable), which isn't documented in MDN and isn't implemented in node.
|
380
|
+
* https://github.com/whatwg/streams/commit/8d7a0bf26eb2cc23e884ddbaac7c1da4b91cf2bc
|
381
|
+
*/
|
382
|
+
declare function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>): ReadableStream<T>;
|
383
|
+
|
384
|
+
/**
|
385
|
+
* A stream wrapper to send custom JSON-encoded data back to the client.
|
386
|
+
*/
|
387
|
+
declare class experimental_StreamData {
|
388
|
+
private encoder;
|
389
|
+
private controller;
|
390
|
+
stream: TransformStream<Uint8Array, Uint8Array>;
|
391
|
+
private isClosedPromise;
|
392
|
+
private isClosedPromiseResolver;
|
393
|
+
private isClosed;
|
394
|
+
private data;
|
395
|
+
constructor();
|
396
|
+
close(): Promise<void>;
|
397
|
+
append(value: JSONValue): void;
|
398
|
+
}
|
399
|
+
/**
|
400
|
+
* A TransformStream for LLMs that do not have their own transform stream handlers managing encoding (e.g. OpenAIStream has one for function call handling).
|
401
|
+
* This assumes every chunk is a 'text' chunk.
|
402
|
+
*/
|
403
|
+
declare function createStreamDataTransformer(experimental_streamData: boolean | undefined): TransformStream<any, any>;
|
331
404
|
|
332
405
|
/**
|
333
406
|
* A utility class for streaming text responses.
|
334
407
|
*/
|
335
408
|
declare class StreamingTextResponse extends Response {
|
336
|
-
constructor(res: ReadableStream, init?: ResponseInit);
|
409
|
+
constructor(res: ReadableStream, init?: ResponseInit, data?: experimental_StreamData);
|
337
410
|
}
|
338
411
|
/**
|
339
412
|
* A utility function to stream a ReadableStream to a Node.js response-like object.
|
@@ -343,9 +416,9 @@ declare function streamToResponse(res: ReadableStream, response: ServerResponse,
|
|
343
416
|
status?: number;
|
344
417
|
}): void;
|
345
418
|
|
346
|
-
declare function HuggingFaceStream(res: AsyncGenerator<any>, callbacks?:
|
419
|
+
declare function HuggingFaceStream(res: AsyncGenerator<any>, callbacks?: AIStreamCallbacksAndOptions): ReadableStream;
|
347
420
|
|
348
|
-
declare function CohereStream(reader: Response, callbacks?:
|
421
|
+
declare function CohereStream(reader: Response, callbacks?: AIStreamCallbacksAndOptions): ReadableStream;
|
349
422
|
|
350
423
|
interface CompletionChunk {
|
351
424
|
/**
|
@@ -372,10 +445,10 @@ interface CompletionChunk {
|
|
372
445
|
* or the return value of `await client.completions.create({ stream: true })`
|
373
446
|
* from the `@anthropic-ai/sdk` package.
|
374
447
|
*/
|
375
|
-
declare function AnthropicStream(res: Response | AsyncIterable<CompletionChunk>, cb?:
|
448
|
+
declare function AnthropicStream(res: Response | AsyncIterable<CompletionChunk>, cb?: AIStreamCallbacksAndOptions): ReadableStream;
|
376
449
|
|
377
|
-
declare function LangChainStream(callbacks?:
|
378
|
-
stream: ReadableStream<
|
450
|
+
declare function LangChainStream(callbacks?: AIStreamCallbacksAndOptions): {
|
451
|
+
stream: ReadableStream<any>;
|
379
452
|
handlers: {
|
380
453
|
handleLLMNewToken: (token: string) => Promise<void>;
|
381
454
|
handleLLMStart: (_llm: any, _prompts: string[], runId: string) => Promise<void>;
|
@@ -409,9 +482,49 @@ declare function LangChainStream(callbacks?: AIStreamCallbacks): {
|
|
409
482
|
* return new StreamingTextResponse(stream)
|
410
483
|
*
|
411
484
|
*/
|
412
|
-
declare function ReplicateStream(res: Prediction, cb?:
|
485
|
+
declare function ReplicateStream(res: Prediction, cb?: AIStreamCallbacksAndOptions): Promise<ReadableStream>;
|
413
486
|
|
414
487
|
declare const nanoid: (size?: number | undefined) => string;
|
415
|
-
declare function createChunkDecoder(): (chunk: Uint8Array | undefined) =>
|
488
|
+
declare function createChunkDecoder(complex?: boolean): (chunk: Uint8Array | undefined) => any;
|
489
|
+
|
490
|
+
/**
|
491
|
+
* The map of prefixes for data in the stream
|
492
|
+
*
|
493
|
+
* - 0: Text from the LLM response
|
494
|
+
* - 1: (OpenAI) function_call responses
|
495
|
+
* - 2: custom JSON added by the user using `Data`
|
496
|
+
*
|
497
|
+
* Example:
|
498
|
+
* ```
|
499
|
+
* 0:Vercel
|
500
|
+
* 0:'s
|
501
|
+
* 0: AI
|
502
|
+
* 0: AI
|
503
|
+
* 0: SDK
|
504
|
+
* 0: is great
|
505
|
+
* 0:!
|
506
|
+
* 2: { "someJson": "value" }
|
507
|
+
* 1: {"function_call": {"name": "get_current_weather", "arguments": "{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}
|
508
|
+
*```
|
509
|
+
*/
|
510
|
+
declare const StreamStringPrefixes: {
|
511
|
+
readonly text: 0;
|
512
|
+
readonly function_call: 1;
|
513
|
+
readonly data: 2;
|
514
|
+
};
|
515
|
+
declare const isStreamStringEqualToType: (type: keyof typeof StreamStringPrefixes, value: string) => value is `0:${string}\n` | `1:${string}\n` | `2:${string}\n`;
|
516
|
+
/**
|
517
|
+
* Prepends a string with a prefix from the `StreamChunkPrefixes`, JSON-ifies it, and appends a new line.
|
518
|
+
*/
|
519
|
+
declare const getStreamString: (type: keyof typeof StreamStringPrefixes, value: JSONValue) => StreamString;
|
520
|
+
type StreamString = `${(typeof StreamStringPrefixes)[keyof typeof StreamStringPrefixes]}:${string}\n`;
|
521
|
+
declare const getStreamStringTypeAndValue: (line: string) => {
|
522
|
+
type: keyof typeof StreamStringPrefixes;
|
523
|
+
value: string;
|
524
|
+
};
|
525
|
+
/**
|
526
|
+
* A header sent to the client so it knows how to handle parsing the stream (as a deprecated text response or using the new prefixed protocol)
|
527
|
+
*/
|
528
|
+
declare const COMPLEX_HEADER = "X-Experimental-Stream-Data";
|
416
529
|
|
417
|
-
export { AIStream,
|
530
|
+
export { AIStream, AIStreamCallbacksAndOptions, AIStreamParser, AnthropicStream, COMPLEX_HEADER, ChatRequest, ChatRequestOptions, CohereStream, CreateMessage, FunctionCallHandler, FunctionCallPayload, HuggingFaceStream, JSONValue, LangChainStream, Message, OpenAIStream, OpenAIStreamCallbacks, ReplicateStream, RequestOptions, StreamString, StreamStringPrefixes, StreamingTextResponse, UseChatOptions, UseCompletionOptions, createCallbacksTransformer, createChunkDecoder, createEventStreamTransformer, createStreamDataTransformer, experimental_StreamData, getStreamString, getStreamStringTypeAndValue, isStreamStringEqualToType, nanoid, readableFromAsyncIterable, streamToResponse, trimStartOfStreamHelper };
|