@xsai/stream-text 0.0.13 → 0.0.15
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.js +20 -9
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { chatCompletion } from '@xsai/shared-chat-completion';
|
|
2
2
|
|
|
3
|
+
const dataHeaderPrefix = "data: ";
|
|
4
|
+
const dataErrorPrefix = `{"error":`;
|
|
3
5
|
const streamText = async (options) => await chatCompletion({
|
|
4
6
|
...options,
|
|
5
7
|
stream: true
|
|
@@ -13,16 +15,25 @@ const streamText = async (options) => await chatCompletion({
|
|
|
13
15
|
const rawChunkStream = res.body.pipeThrough(new TransformStream({
|
|
14
16
|
transform: (chunk, controller) => {
|
|
15
17
|
for (const line of decoder.decode(chunk).split("\n").filter((line2) => line2)) {
|
|
16
|
-
if (line
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
18
|
+
if (!line || !line.startsWith(dataHeaderPrefix)) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (line.startsWith(dataErrorPrefix)) {
|
|
22
|
+
controller.error(new Error(`Error from server: ${line}`));
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const lineWithoutPrefix = line.slice(dataHeaderPrefix.length);
|
|
26
|
+
if (lineWithoutPrefix === "[DONE]") {
|
|
25
27
|
controller.terminate();
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const data = JSON.parse(line.slice(6));
|
|
31
|
+
controller.enqueue(data);
|
|
32
|
+
if (data.choices[0].finish_reason) {
|
|
33
|
+
finishReason = data.choices[0].finish_reason;
|
|
34
|
+
}
|
|
35
|
+
if (data.usage) {
|
|
36
|
+
usage = data.usage;
|
|
26
37
|
}
|
|
27
38
|
}
|
|
28
39
|
}
|