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