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