Spaces:
Paused
Paused
Commit
·
24fe16c
1
Parent(s):
e86f9d8
Update utils/server/index.ts
Browse files- utils/server/index.ts +41 -18
utils/server/index.ts
CHANGED
|
@@ -74,31 +74,54 @@ export const LLMStream = async (
|
|
| 74 |
const stream = new ReadableStream({
|
| 75 |
async start(controller) {
|
| 76 |
const onParse = (event: ParsedEvent | ReconnectInterval) => {
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
const queue = encoder.encode(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
|
|
|
|
|
|
| 89 |
controller.enqueue(queue);
|
| 90 |
-
} catch (e) {
|
| 91 |
-
controller.error(e);
|
| 92 |
}
|
|
|
|
|
|
|
|
|
|
| 93 |
}
|
| 94 |
-
}
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
});
|
| 103 |
|
| 104 |
return stream;
|
|
|
|
| 74 |
const stream = new ReadableStream({
|
| 75 |
async start(controller) {
|
| 76 |
const onParse = (event: ParsedEvent | ReconnectInterval) => {
|
| 77 |
+
console.log(event);
|
| 78 |
+
if (event.type === 'event') {
|
| 79 |
+
const data = event.data;
|
| 80 |
+
if (data === '') {
|
| 81 |
+
controller.close();
|
| 82 |
+
return;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
try {
|
| 86 |
+
const json = JSON.parse(data);
|
| 87 |
+
|
| 88 |
+
// New condition to handle Python API format
|
| 89 |
+
if (json.choices && json.choices[0].message) {
|
| 90 |
+
const text = json.choices[0].message.content;
|
| 91 |
+
const finishReason = json.choices[0].finish_reason;
|
| 92 |
+
|
| 93 |
+
if (finishReason === 'stop') {
|
| 94 |
+
controller.close();
|
| 95 |
+
return;
|
| 96 |
+
}
|
| 97 |
|
| 98 |
+
const queue = encoder.encode(text);
|
| 99 |
+
controller.enqueue(queue);
|
| 100 |
+
}
|
| 101 |
+
// Old condition to handle existing format
|
| 102 |
+
else if (json.choices && json.choices[0].delta) {
|
| 103 |
+
if (json.choices[0].finish_reason != null) {
|
| 104 |
+
controller.close();
|
| 105 |
+
return;
|
| 106 |
+
}
|
| 107 |
|
| 108 |
+
const text = json.choices[0].delta.content;
|
| 109 |
+
const queue = encoder.encode(text);
|
| 110 |
controller.enqueue(queue);
|
|
|
|
|
|
|
| 111 |
}
|
| 112 |
+
|
| 113 |
+
} catch (e) {
|
| 114 |
+
controller.error(e);
|
| 115 |
}
|
| 116 |
+
}
|
| 117 |
+
};
|
| 118 |
|
| 119 |
+
const parser = createParser(onParse);
|
| 120 |
|
| 121 |
+
for await (const chunk of res.body as any) {
|
| 122 |
+
parser.feed(decoder.decode(chunk));
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
});
|
| 126 |
|
| 127 |
return stream;
|