@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.
Files changed (2) hide show
  1. package/dist/index.js +20 -9
  2. 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 !== "data: [DONE]") {
17
- const data = JSON.parse(line.slice(6));
18
- controller.enqueue(data);
19
- if (data.choices[0].finish_reason) {
20
- finishReason = data.choices[0].finish_reason;
21
- }
22
- if (data.usage)
23
- usage = data.usage;
24
- } else {
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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xsai/stream-text",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "type": "module",
5
5
  "author": "Moeru AI",
6
6
  "license": "MIT",