Spaces:
Paused
Paused
Commit
·
12e11a1
1
Parent(s):
da4070d
Update utils/server/index.ts
Browse files- utils/server/index.ts +14 -9
utils/server/index.ts
CHANGED
@@ -73,32 +73,37 @@ export const LLMStream = async (
|
|
73 |
|
74 |
const stream = new ReadableStream({
|
75 |
async start(controller) {
|
76 |
-
const onParse = (
|
77 |
-
if (
|
78 |
-
const
|
79 |
|
80 |
try {
|
81 |
-
const json = JSON.parse(
|
82 |
-
if (json.choices[0].finish_reason
|
83 |
controller.close();
|
84 |
return;
|
85 |
}
|
86 |
-
const text = json.choices[0].
|
87 |
const queue = encoder.encode(text);
|
88 |
controller.enqueue(queue);
|
89 |
} catch (e) {
|
90 |
controller.error(e);
|
91 |
}
|
|
|
|
|
92 |
}
|
93 |
};
|
94 |
|
95 |
-
const parser = createParser(onParse);
|
96 |
-
|
97 |
for await (const chunk of res.body as any) {
|
98 |
-
|
|
|
|
|
|
|
|
|
99 |
}
|
100 |
},
|
101 |
});
|
102 |
|
|
|
103 |
return stream;
|
104 |
};
|
|
|
73 |
|
74 |
const stream = new ReadableStream({
|
75 |
async start(controller) {
|
76 |
+
const onParse = (data) => {
|
77 |
+
if (data.startsWith('data:')) {
|
78 |
+
const jsonString = data.replace('data: ', '').trim();
|
79 |
|
80 |
try {
|
81 |
+
const json = JSON.parse(jsonString);
|
82 |
+
if (json.choices[0].finish_reason === 'stop') {
|
83 |
controller.close();
|
84 |
return;
|
85 |
}
|
86 |
+
const text = json.choices[0].message.content;
|
87 |
const queue = encoder.encode(text);
|
88 |
controller.enqueue(queue);
|
89 |
} catch (e) {
|
90 |
controller.error(e);
|
91 |
}
|
92 |
+
} else if (data.startsWith('event: done')) {
|
93 |
+
controller.close();
|
94 |
}
|
95 |
};
|
96 |
|
|
|
|
|
97 |
for await (const chunk of res.body as any) {
|
98 |
+
const dataString = decoder.decode(chunk);
|
99 |
+
const dataParts = dataString.split("\n\n");
|
100 |
+
dataParts.forEach(part => {
|
101 |
+
onParse(part);
|
102 |
+
});
|
103 |
}
|
104 |
},
|
105 |
});
|
106 |
|
107 |
+
|
108 |
return stream;
|
109 |
};
|