ai 2.0.1 → 2.1.2
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 +48 -8
- package/dist/index.mjs +234 -22
- package/package.json +20 -8
- package/react/dist/index.d.ts +206 -3
- package/react/dist/index.mjs +384 -7
- package/svelte/dist/index.d.ts +194 -4
- package/svelte/dist/index.mjs +779 -7
- package/{react/dist/types-f862f74a.d.ts → vue/dist/index.d.ts} +72 -1
- package/vue/dist/index.js +384 -0
- package/vue/dist/index.mjs +349 -0
- package/dist/ai-stream.d.ts +0 -18
- package/dist/ai-stream.js +0 -132
- package/dist/ai-stream.mjs +0 -13
- package/dist/anthropic-stream.d.ts +0 -5
- package/dist/anthropic-stream.js +0 -133
- package/dist/anthropic-stream.mjs +0 -8
- package/dist/chunk-265FSSO4.mjs +0 -91
- package/dist/chunk-2L3ZO4UM.mjs +0 -45
- package/dist/chunk-GT4HKF2X.mjs +0 -33
- package/dist/chunk-JGDC3BXD.mjs +0 -22
- package/dist/chunk-NK2CVBLI.mjs +0 -38
- package/dist/chunk-PEYAHBDF.mjs +0 -43
- package/dist/chunk-TJMME6CL.mjs +0 -24
- package/dist/huggingface-stream.d.ts +0 -5
- package/dist/huggingface-stream.js +0 -121
- package/dist/huggingface-stream.mjs +0 -8
- package/dist/index.test.d.ts +0 -2
- package/dist/index.test.js +0 -12
- package/dist/index.test.mjs +0 -10
- package/dist/langchain-stream.d.ts +0 -12
- package/dist/langchain-stream.js +0 -102
- package/dist/langchain-stream.mjs +0 -8
- package/dist/openai-stream.d.ts +0 -5
- package/dist/openai-stream.js +0 -144
- package/dist/openai-stream.mjs +0 -8
- package/dist/streaming-text-response.d.ts +0 -17
- package/dist/streaming-text-response.js +0 -75
- package/dist/streaming-text-response.mjs +0 -9
- package/react/dist/chunk-5PP6W52J.mjs +0 -202
- package/react/dist/chunk-6EH3SWMP.mjs +0 -55
- package/react/dist/chunk-PW6HSU2N.mjs +0 -154
- package/react/dist/use-chat.d.ts +0 -42
- package/react/dist/use-chat.js +0 -276
- package/react/dist/use-chat.mjs +0 -8
- package/react/dist/use-completion.d.ts +0 -47
- package/react/dist/use-completion.js +0 -229
- package/react/dist/use-completion.mjs +0 -8
- package/svelte/dist/chunk-6USBQIV6.mjs +0 -177
- package/svelte/dist/chunk-BQ64GHZ3.mjs +0 -136
- package/svelte/dist/chunk-CENOSGDG.mjs +0 -493
- package/svelte/dist/types-f862f74a.d.ts +0 -123
- package/svelte/dist/use-chat.d.ts +0 -39
- package/svelte/dist/use-chat.js +0 -680
- package/svelte/dist/use-chat.mjs +0 -7
- package/svelte/dist/use-completion.d.ts +0 -38
- package/svelte/dist/use-completion.js +0 -640
- package/svelte/dist/use-completion.mjs +0 -7
package/dist/index.d.ts
CHANGED
@@ -1,10 +1,50 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
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,26 +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
|
-
|
3
|
-
} from "
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
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
|
+
}
|
24
236
|
export {
|
25
237
|
AIStream,
|
26
238
|
AnthropicStream,
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "ai",
|
3
|
-
"version": "2.
|
3
|
+
"version": "2.1.2",
|
4
4
|
"license": "Apache-2.0",
|
5
5
|
"sideEffects": false,
|
6
6
|
"main": "./dist/index.js",
|
@@ -9,7 +9,8 @@
|
|
9
9
|
"files": [
|
10
10
|
"dist/**/*",
|
11
11
|
"react/dist/**/*",
|
12
|
-
"svelte/dist/**/*"
|
12
|
+
"svelte/dist/**/*",
|
13
|
+
"vue/dist/**/*"
|
13
14
|
],
|
14
15
|
"exports": {
|
15
16
|
"./package.json": "./package.json",
|
@@ -30,6 +31,12 @@
|
|
30
31
|
"import": "./svelte/dist/index.mjs",
|
31
32
|
"module": "./svelte/dist/index.mjs",
|
32
33
|
"require": "./svelte/dist/index.js"
|
34
|
+
},
|
35
|
+
"./vue": {
|
36
|
+
"types": "./vue/dist/index.d.ts",
|
37
|
+
"import": "./vue/dist/index.mjs",
|
38
|
+
"module": "./vue/dist/index.mjs",
|
39
|
+
"require": "./vue/dist/index.js"
|
33
40
|
}
|
34
41
|
},
|
35
42
|
"jest": {
|
@@ -40,7 +47,8 @@
|
|
40
47
|
"eventsource-parser": "1.0.0",
|
41
48
|
"nanoid": "^3.3.6",
|
42
49
|
"sswr": "^1.10.0",
|
43
|
-
"swr": "2.1.5"
|
50
|
+
"swr": "2.1.5",
|
51
|
+
"swrv": "1.0.3"
|
44
52
|
},
|
45
53
|
"devDependencies": {
|
46
54
|
"@edge-runtime/jest-environment": "1.1.0-beta.31",
|
@@ -53,12 +61,13 @@
|
|
53
61
|
"ts-jest": "29.0.3",
|
54
62
|
"tsup": "^6.7.0",
|
55
63
|
"typescript": "^4.5.3",
|
56
|
-
"
|
57
|
-
"
|
64
|
+
"eslint-config-vercel-ai": "0.0.0",
|
65
|
+
"@vercel/ai-tsconfig": "0.0.0"
|
58
66
|
},
|
59
67
|
"peerDependencies": {
|
60
68
|
"react": "^18.0.0",
|
61
|
-
"svelte": "^3.29.0"
|
69
|
+
"svelte": "^3.29.0",
|
70
|
+
"vue": "^3.3.4"
|
62
71
|
},
|
63
72
|
"peerDependenciesMeta": {
|
64
73
|
"react": {
|
@@ -66,6 +75,9 @@
|
|
66
75
|
},
|
67
76
|
"svelte": {
|
68
77
|
"optional": true
|
78
|
+
},
|
79
|
+
"vue": {
|
80
|
+
"optional": true
|
69
81
|
}
|
70
82
|
},
|
71
83
|
"engines": {
|
@@ -76,11 +88,11 @@
|
|
76
88
|
},
|
77
89
|
"scripts": {
|
78
90
|
"build": "tsup",
|
79
|
-
"clean": "rm -rf
|
91
|
+
"clean": "rm -rf dist && rm -rf react/dist && rm -rf svelte/dist && rm -rf vue/dist",
|
80
92
|
"dev": "tsup --watch",
|
81
93
|
"lint": "eslint \"./**/*.ts*\"",
|
82
94
|
"type-check": "tsc --noEmit",
|
83
95
|
"prettier-check": "prettier --check \"./**/*.ts*\"",
|
84
|
-
"test": "jest --env @edge-runtime/jest-environment .test.ts && jest --env node .test.ts"
|
96
|
+
"test": "jest --forceExit --env @edge-runtime/jest-environment .test.ts && jest --forceExit --env node .test.ts"
|
85
97
|
}
|
86
98
|
}
|
package/react/dist/index.d.ts
CHANGED
@@ -1,3 +1,206 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
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 };
|