ai 2.1.0 → 2.1.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.
Files changed (71) hide show
  1. package/README.md +89 -0
  2. package/dist/index.d.ts +48 -8
  3. package/dist/index.mjs +234 -26
  4. package/package.json +4 -4
  5. package/react/dist/index.d.ts +206 -3
  6. package/react/dist/index.js +2 -1
  7. package/react/dist/index.mjs +385 -7
  8. package/svelte/dist/index.d.ts +194 -4
  9. package/svelte/dist/index.js +2 -1
  10. package/svelte/dist/index.mjs +780 -7
  11. package/vue/dist/index.d.ts +194 -4
  12. package/vue/dist/index.mjs +345 -7
  13. package/dist/ai-stream.d.ts +0 -18
  14. package/dist/ai-stream.js +0 -132
  15. package/dist/ai-stream.mjs +0 -15
  16. package/dist/anthropic-stream.d.ts +0 -5
  17. package/dist/anthropic-stream.js +0 -133
  18. package/dist/anthropic-stream.mjs +0 -10
  19. package/dist/chunk-2JQWCLY2.mjs +0 -70
  20. package/dist/chunk-7KLTYB74.mjs +0 -70
  21. package/dist/chunk-BJMBMGA3.mjs +0 -34
  22. package/dist/chunk-KKQRUR3E.mjs +0 -51
  23. package/dist/chunk-RBP6ONSV.mjs +0 -45
  24. package/dist/chunk-TWW2ODJW.mjs +0 -32
  25. package/dist/chunk-U2OQ6HW6.mjs +0 -41
  26. package/dist/chunk-UJV6VDVU.mjs +0 -97
  27. package/dist/huggingface-stream.d.ts +0 -5
  28. package/dist/huggingface-stream.js +0 -121
  29. package/dist/huggingface-stream.mjs +0 -10
  30. package/dist/index.test.d.ts +0 -2
  31. package/dist/index.test.js +0 -568
  32. package/dist/index.test.mjs +0 -286
  33. package/dist/langchain-stream.d.ts +0 -12
  34. package/dist/langchain-stream.js +0 -102
  35. package/dist/langchain-stream.mjs +0 -10
  36. package/dist/openai-stream.d.ts +0 -5
  37. package/dist/openai-stream.js +0 -144
  38. package/dist/openai-stream.mjs +0 -10
  39. package/dist/streaming-text-response.d.ts +0 -17
  40. package/dist/streaming-text-response.js +0 -75
  41. package/dist/streaming-text-response.mjs +0 -11
  42. package/react/dist/chunk-5PP6W52J.mjs +0 -202
  43. package/react/dist/chunk-6EH3SWMP.mjs +0 -55
  44. package/react/dist/chunk-PW6HSU2N.mjs +0 -154
  45. package/react/dist/types-f862f74a.d.ts +0 -123
  46. package/react/dist/use-chat.d.ts +0 -42
  47. package/react/dist/use-chat.js +0 -276
  48. package/react/dist/use-chat.mjs +0 -8
  49. package/react/dist/use-completion.d.ts +0 -47
  50. package/react/dist/use-completion.js +0 -229
  51. package/react/dist/use-completion.mjs +0 -8
  52. package/svelte/dist/chunk-6USBQIV6.mjs +0 -177
  53. package/svelte/dist/chunk-BQ64GHZ3.mjs +0 -136
  54. package/svelte/dist/chunk-CENOSGDG.mjs +0 -493
  55. package/svelte/dist/types-f862f74a.d.ts +0 -123
  56. package/svelte/dist/use-chat.d.ts +0 -39
  57. package/svelte/dist/use-chat.js +0 -680
  58. package/svelte/dist/use-chat.mjs +0 -7
  59. package/svelte/dist/use-completion.d.ts +0 -38
  60. package/svelte/dist/use-completion.js +0 -640
  61. package/svelte/dist/use-completion.mjs +0 -7
  62. package/vue/dist/chunk-FT26CHLO.mjs +0 -137
  63. package/vue/dist/chunk-OYI6GFBM.mjs +0 -178
  64. package/vue/dist/chunk-WXH4YPZV.mjs +0 -54
  65. package/vue/dist/types-f862f74a.d.ts +0 -123
  66. package/vue/dist/use-chat.d.ts +0 -39
  67. package/vue/dist/use-chat.js +0 -252
  68. package/vue/dist/use-chat.mjs +0 -7
  69. package/vue/dist/use-completion.d.ts +0 -38
  70. package/vue/dist/use-completion.js +0 -212
  71. package/vue/dist/use-completion.mjs +0 -7
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # Vercel AI SDK
2
+
3
+ The Vercel AI SDK is **a library for building edge-ready AI-powered streaming text and chat UIs**.
4
+
5
+ ## Features
6
+
7
+ - [SWR](https://swr.vercel.app)-powered React, Svelte and Vue 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), and [HuggingFace](https://huggingface.co)
9
+ - [Edge Runtime](https://edge-runtime.vercel.app/) compatibility
10
+ - Callbacks for saving completed streaming responses to a database (in the same request)
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ pnpm install ai
16
+ ```
17
+
18
+ ## Example: An AI Chatbot with Next.js and OpenAI
19
+
20
+ With the Vercel AI SDK, you can build a ChatGPT-like app in just a few lines of code:
21
+
22
+ ```tsx
23
+ // ./app/api/chat/route.js
24
+ import { Configuration, OpenAIApi } from 'openai-edge'
25
+ import { OpenAIStream, StreamingTextResponse } from 'ai'
26
+
27
+ const config = new Configuration({
28
+ apiKey: process.env.OPENAI_API_KEY
29
+ })
30
+ const openai = new OpenAIApi(config)
31
+
32
+ export const runtime = 'edge'
33
+
34
+ export async function POST(req) {
35
+ const { messages } = await req.json()
36
+ const response = await openai.createChatCompletion({
37
+ model: 'gpt-4',
38
+ stream: true,
39
+ messages
40
+ })
41
+ const stream = OpenAIStream(response)
42
+ return new StreamingTextResponse(stream)
43
+ }
44
+ ```
45
+
46
+ ```tsx
47
+ // ./app/page.js
48
+ 'use client'
49
+
50
+ import { useChat } from 'ai/react'
51
+
52
+ export default function Chat() {
53
+ const { messages, input, handleInputChange, handleSubmit } = useChat()
54
+
55
+ return (
56
+ <div>
57
+ {messages.map(m => (
58
+ <div key={m.id}>
59
+ {m.role}: {m.content}
60
+ </div>
61
+ ))}
62
+
63
+ <form onSubmit={handleSubmit}>
64
+ <input
65
+ value={input}
66
+ placeholder="Say something..."
67
+ onChange={handleInputChange}
68
+ />
69
+ </form>
70
+ </div>
71
+ )
72
+ }
73
+ ```
74
+
75
+ ---
76
+
77
+ View the full documentation and examples on [play.vercel.ai/docs](https://play.vercel.ai/docs)
78
+
79
+ ## Authors
80
+
81
+ This library is created by [Vercel](https://vercel.com) and [Next.js](https://nextjs.org) team members, with contributions from:
82
+
83
+ - Jared Palmer ([@jaredpalmer](https://twitter.com/jaredpalmer)) - [Vercel](https://vercel.com)
84
+ - Shu Ding ([@shuding\_](https://twitter.com/shuding_)) - [Vercel](https://vercel.com)
85
+ - Max Leiter ([@max_leiter](https://twitter.com/max_leiter)) - [Vercel](https://vercel.com)
86
+ - Malte Ubl ([@cramforce](https://twitter.com/cramforce)) - [Vercel](https://vercel.com)
87
+ - Justin Ridgewell ([@jridgewell](https://github.com/jridgewell)) - [Vercel](https://vercel.com)
88
+
89
+ [Contributors](https://github.com/vercel-labs/ai/graphs/contributors)
package/dist/index.d.ts CHANGED
@@ -1,10 +1,50 @@
1
- export { AIStream, AIStreamCallbacks, AIStreamParser, createCallbacksTransformer, createEventStreamTransformer, trimStartOfStreamHelper } from './ai-stream.js';
2
- export { OpenAIStream } from './openai-stream.js';
3
- export { StreamingTextResponse, streamToResponse } from './streaming-text-response.js';
4
- export { HuggingFaceStream } from './huggingface-stream.js';
5
- export { AnthropicStream } from './anthropic-stream.js';
6
- export { LangChainStream } from './langchain-stream.js';
7
- import 'node:http';
1
+ import { ServerResponse } from 'node:http';
2
+
3
+ interface AIStreamCallbacks {
4
+ onStart?: () => Promise<void>;
5
+ onCompletion?: (completion: string) => Promise<void>;
6
+ onToken?: (token: string) => Promise<void>;
7
+ }
8
+ interface AIStreamParser {
9
+ (data: string): string | void;
10
+ }
11
+ declare function createEventStreamTransformer(customParser: AIStreamParser): TransformStream<Uint8Array, string>;
12
+ /**
13
+ * This stream forks input stream, allowing us to use the result as a
14
+ * bytestream of the messages and pass the messages to our callback interface.
15
+ */
16
+ declare function createCallbacksTransformer(callbacks: AIStreamCallbacks | undefined): TransformStream<string, Uint8Array>;
17
+ declare function trimStartOfStreamHelper(): (text: string) => string;
18
+ declare function AIStream(res: Response, customParser: AIStreamParser, callbacks?: AIStreamCallbacks): ReadableStream;
19
+
20
+ declare function OpenAIStream(res: Response, cb?: AIStreamCallbacks): ReadableStream;
21
+
22
+ /**
23
+ * A utility class for streaming text responses.
24
+ */
25
+ declare class StreamingTextResponse extends Response {
26
+ constructor(res: ReadableStream, init?: ResponseInit);
27
+ }
28
+ /**
29
+ * A utility function to stream a ReadableStream to a Node.js response-like object.
30
+ */
31
+ declare function streamToResponse(res: ReadableStream, response: ServerResponse, init?: {
32
+ headers?: Record<string, string>;
33
+ status?: number;
34
+ }): void;
35
+
36
+ declare function HuggingFaceStream(res: AsyncGenerator<any>, callbacks?: AIStreamCallbacks): ReadableStream;
37
+
38
+ declare function AnthropicStream(res: Response, cb?: AIStreamCallbacks): ReadableStream;
39
+
40
+ declare function LangChainStream(callbacks?: AIStreamCallbacks): {
41
+ stream: ReadableStream<Uint8Array>;
42
+ handlers: {
43
+ handleLLMNewToken: (token: string) => Promise<void>;
44
+ handleChainEnd: () => Promise<void>;
45
+ handleLLMError: (e: any) => Promise<void>;
46
+ };
47
+ };
8
48
 
9
49
  /**
10
50
  * Shared types between the API and UI packages.
@@ -128,4 +168,4 @@ type UseCompletionOptions = {
128
168
  body?: object;
129
169
  };
130
170
 
131
- export { CreateMessage, Message, UseChatOptions, UseCompletionOptions };
171
+ export { AIStream, AIStreamCallbacks, AIStreamParser, AnthropicStream, CreateMessage, HuggingFaceStream, LangChainStream, Message, OpenAIStream, StreamingTextResponse, UseChatOptions, UseCompletionOptions, createCallbacksTransformer, createEventStreamTransformer, streamToResponse, trimStartOfStreamHelper };
package/dist/index.mjs CHANGED
@@ -1,30 +1,238 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+
41
+ // streams/ai-stream.ts
1
42
  import {
2
- init_streams
3
- } from "./chunk-7KLTYB74.mjs";
4
- import {
5
- AnthropicStream
6
- } from "./chunk-TWW2ODJW.mjs";
7
- import {
8
- HuggingFaceStream
9
- } from "./chunk-KKQRUR3E.mjs";
10
- import {
11
- LangChainStream
12
- } from "./chunk-U2OQ6HW6.mjs";
13
- import {
14
- OpenAIStream
15
- } from "./chunk-BJMBMGA3.mjs";
16
- import {
17
- AIStream,
18
- createCallbacksTransformer,
19
- createEventStreamTransformer,
20
- trimStartOfStreamHelper
21
- } from "./chunk-UJV6VDVU.mjs";
22
- import {
23
- StreamingTextResponse,
24
- streamToResponse
25
- } from "./chunk-RBP6ONSV.mjs";
26
- import "./chunk-2JQWCLY2.mjs";
27
- init_streams();
43
+ createParser
44
+ } from "eventsource-parser";
45
+ function createEventStreamTransformer(customParser) {
46
+ const decoder = new TextDecoder();
47
+ let parser;
48
+ return new TransformStream({
49
+ start(controller) {
50
+ return __async(this, null, function* () {
51
+ function onParse(event) {
52
+ if (event.type === "event") {
53
+ const data = event.data;
54
+ if (data === "[DONE]") {
55
+ controller.terminate();
56
+ return;
57
+ }
58
+ const message = customParser(data);
59
+ if (message)
60
+ controller.enqueue(message);
61
+ }
62
+ }
63
+ parser = createParser(onParse);
64
+ });
65
+ },
66
+ transform(chunk) {
67
+ parser.feed(decoder.decode(chunk));
68
+ }
69
+ });
70
+ }
71
+ function createCallbacksTransformer(callbacks) {
72
+ const encoder = new TextEncoder();
73
+ let fullResponse = "";
74
+ const { onStart, onToken, onCompletion } = callbacks || {};
75
+ return new TransformStream({
76
+ start() {
77
+ return __async(this, null, function* () {
78
+ if (onStart)
79
+ yield onStart();
80
+ });
81
+ },
82
+ transform(message, controller) {
83
+ return __async(this, null, function* () {
84
+ controller.enqueue(encoder.encode(message));
85
+ if (onToken)
86
+ yield onToken(message);
87
+ if (onCompletion)
88
+ fullResponse += message;
89
+ });
90
+ },
91
+ flush() {
92
+ return __async(this, null, function* () {
93
+ yield onCompletion == null ? void 0 : onCompletion(fullResponse);
94
+ });
95
+ }
96
+ });
97
+ }
98
+ function trimStartOfStreamHelper() {
99
+ let start = true;
100
+ return (text) => {
101
+ if (start)
102
+ text = text.trimStart();
103
+ if (text)
104
+ start = false;
105
+ return text;
106
+ };
107
+ }
108
+ function AIStream(res, customParser, callbacks) {
109
+ if (!res.ok) {
110
+ throw new Error(
111
+ `Failed to convert the response to stream. Received status code: ${res.status}.`
112
+ );
113
+ }
114
+ const stream = res.body || new ReadableStream({
115
+ start(controller) {
116
+ controller.close();
117
+ }
118
+ });
119
+ return stream.pipeThrough(createEventStreamTransformer(customParser)).pipeThrough(createCallbacksTransformer(callbacks));
120
+ }
121
+
122
+ // streams/openai-stream.ts
123
+ function parseOpenAIStream() {
124
+ const trimStartOfStream = trimStartOfStreamHelper();
125
+ return (data) => {
126
+ var _a, _b, _c, _d, _e;
127
+ const json = JSON.parse(data);
128
+ const text = trimStartOfStream(
129
+ (_e = (_d = (_b = (_a = json.choices[0]) == null ? void 0 : _a.delta) == null ? void 0 : _b.content) != null ? _d : (_c = json.choices[0]) == null ? void 0 : _c.text) != null ? _e : ""
130
+ );
131
+ return text;
132
+ };
133
+ }
134
+ function OpenAIStream(res, cb) {
135
+ return AIStream(res, parseOpenAIStream(), cb);
136
+ }
137
+
138
+ // streams/streaming-text-response.ts
139
+ var StreamingTextResponse = class extends Response {
140
+ constructor(res, init) {
141
+ super(res, __spreadProps(__spreadValues({}, init), {
142
+ status: 200,
143
+ headers: __spreadValues({
144
+ "Content-Type": "text/plain; charset=utf-8"
145
+ }, init == null ? void 0 : init.headers)
146
+ }));
147
+ }
148
+ };
149
+ function streamToResponse(res, response, init) {
150
+ response.writeHead((init == null ? void 0 : init.status) || 200, __spreadValues({
151
+ "Content-Type": "text/plain; charset=utf-8"
152
+ }, init == null ? void 0 : init.headers));
153
+ const reader = res.getReader();
154
+ function read() {
155
+ reader.read().then(({ done, value }) => {
156
+ if (done) {
157
+ response.end();
158
+ return;
159
+ }
160
+ response.write(value);
161
+ read();
162
+ });
163
+ }
164
+ read();
165
+ }
166
+
167
+ // streams/huggingface-stream.ts
168
+ function createParser2(res) {
169
+ const trimStartOfStream = trimStartOfStreamHelper();
170
+ return new ReadableStream({
171
+ pull(controller) {
172
+ return __async(this, null, function* () {
173
+ var _a2, _b;
174
+ const { value, done } = yield res.next();
175
+ if (done) {
176
+ controller.close();
177
+ return;
178
+ }
179
+ const text = trimStartOfStream((_b = (_a2 = value.token) == null ? void 0 : _a2.text) != null ? _b : "");
180
+ if (!text)
181
+ return;
182
+ if (value.generated_text != null && value.generated_text.length > 0) {
183
+ controller.close();
184
+ return;
185
+ }
186
+ if (text === "</s>" || text === "<|endoftext|>") {
187
+ controller.close();
188
+ } else {
189
+ controller.enqueue(text);
190
+ }
191
+ });
192
+ }
193
+ });
194
+ }
195
+ function HuggingFaceStream(res, callbacks) {
196
+ return createParser2(res).pipeThrough(createCallbacksTransformer(callbacks));
197
+ }
198
+
199
+ // streams/anthropic-stream.ts
200
+ function parseAnthropicStream() {
201
+ let previous = "";
202
+ return (data) => {
203
+ const json = JSON.parse(data);
204
+ const text = json.completion;
205
+ const delta = text.slice(previous.length);
206
+ previous = text;
207
+ return delta;
208
+ };
209
+ }
210
+ function AnthropicStream(res, cb) {
211
+ return AIStream(res, parseAnthropicStream(), cb);
212
+ }
213
+
214
+ // streams/langchain-stream.ts
215
+ function LangChainStream(callbacks) {
216
+ const stream = new TransformStream();
217
+ const writer = stream.writable.getWriter();
218
+ return {
219
+ stream: stream.readable.pipeThrough(createCallbacksTransformer(callbacks)),
220
+ handlers: {
221
+ handleLLMNewToken: (token) => __async(this, null, function* () {
222
+ yield writer.ready;
223
+ yield writer.write(token);
224
+ }),
225
+ handleChainEnd: () => __async(this, null, function* () {
226
+ yield writer.ready;
227
+ yield writer.close();
228
+ }),
229
+ handleLLMError: (e) => __async(this, null, function* () {
230
+ yield writer.ready;
231
+ yield writer.abort(e);
232
+ })
233
+ }
234
+ };
235
+ }
28
236
  export {
29
237
  AIStream,
30
238
  AnthropicStream,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "2.1.0",
3
+ "version": "2.1.3",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -61,8 +61,8 @@
61
61
  "ts-jest": "29.0.3",
62
62
  "tsup": "^6.7.0",
63
63
  "typescript": "^4.5.3",
64
- "@vercel/ai-tsconfig": "0.0.0",
65
- "eslint-config-vercel-ai": "0.0.0"
64
+ "eslint-config-vercel-ai": "0.0.0",
65
+ "@vercel/ai-tsconfig": "0.0.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "react": "^18.0.0",
@@ -88,7 +88,7 @@
88
88
  },
89
89
  "scripts": {
90
90
  "build": "tsup",
91
- "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf react/dist && rm -rf svelte/dist && rm -rf vue/dist",
91
+ "clean": "rm -rf dist && rm -rf react/dist && rm -rf svelte/dist && rm -rf vue/dist",
92
92
  "dev": "tsup --watch",
93
93
  "lint": "eslint \"./**/*.ts*\"",
94
94
  "type-check": "tsc --noEmit",
@@ -1,3 +1,206 @@
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';
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
+ type UseChatHelpers = {
124
+ /** Current messages in the chat */
125
+ messages: Message[];
126
+ /** The error object of the API request */
127
+ error: undefined | Error;
128
+ /**
129
+ * Append a user message to the chat list. This triggers the API call to fetch
130
+ * the assistant's response.
131
+ */
132
+ append: (message: Message | CreateMessage) => Promise<string | null | undefined>;
133
+ /**
134
+ * Reload the last AI chat response for the given chat history. If the last
135
+ * message isn't from the assistant, it will request the API to generate a
136
+ * new response.
137
+ */
138
+ reload: () => Promise<string | null | undefined>;
139
+ /**
140
+ * Abort the current request immediately, keep the generated tokens if any.
141
+ */
142
+ stop: () => void;
143
+ /**
144
+ * Update the `messages` state locally. This is useful when you want to
145
+ * edit the messages on the client, and then trigger the `reload` method
146
+ * manually to regenerate the AI response.
147
+ */
148
+ setMessages: (messages: Message[]) => void;
149
+ /** The current value of the input */
150
+ input: string;
151
+ /** setState-powered method to update the input value */
152
+ setInput: React.Dispatch<React.SetStateAction<string>>;
153
+ /** An input/textarea-ready onChange handler to control the value of the input */
154
+ handleInputChange: (e: any) => void;
155
+ /** Form submission handler to automattically reset input and append a user message */
156
+ handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
157
+ /** Whether the API request is in progress */
158
+ isLoading: boolean;
159
+ };
160
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onResponse, onFinish, onError, headers, body }?: UseChatOptions): UseChatHelpers;
161
+
162
+ type UseCompletionHelpers = {
163
+ /** The current completion result */
164
+ completion: string;
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
+ /** The error object of the API request */
170
+ error: undefined | Error;
171
+ /**
172
+ * Abort the current API request but keep the generated tokens.
173
+ */
174
+ stop: () => void;
175
+ /**
176
+ * Update the `completion` state locally.
177
+ */
178
+ setCompletion: (completion: string) => void;
179
+ /** The current value of the input */
180
+ input: string;
181
+ /** setState-powered method to update the input value */
182
+ setInput: React.Dispatch<React.SetStateAction<string>>;
183
+ /**
184
+ * An input/textarea-ready onChange handler to control the value of the input
185
+ * @example
186
+ * ```jsx
187
+ * <input onChange={handleInputChange} value={input} />
188
+ * ```
189
+ */
190
+ handleInputChange: (e: any) => void;
191
+ /**
192
+ * Form submission handler to automattically reset input and append a user message
193
+ * @example
194
+ * ```jsx
195
+ * <form onSubmit={handleSubmit}>
196
+ * <input onChange={handleInputChange} value={input} />
197
+ * </form>
198
+ * ```
199
+ */
200
+ handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
201
+ /** Whether the API request is in progress */
202
+ isLoading: boolean;
203
+ };
204
+ declare function useCompletion({ api, id, initialCompletion, initialInput, headers, body, onResponse, onFinish, onError }?: UseCompletionOptions): UseCompletionHelpers;
205
+
206
+ export { CreateMessage, Message, UseChatHelpers, UseChatOptions, UseCompletionHelpers, useChat, useCompletion };
@@ -250,7 +250,8 @@ function useChat({
250
250
  return;
251
251
  append({
252
252
  content: input,
253
- role: "user"
253
+ role: "user",
254
+ createdAt: /* @__PURE__ */ new Date()
254
255
  });
255
256
  setInput("");
256
257
  },