Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/platform/nesFetch/node/streamTransformer.ts
13401 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { Completion } from '../common/completionsAPI';
7
8
/**
9
* @throws if data line cannot be parsed as JSON or if it contains an error field.
10
*/
11
export async function* jsonlStreamToCompletions(jsonlStream: AsyncIterable<string>): AsyncGenerator<Completion> {
12
for await (const line of jsonlStream) {
13
if (line.trim() === 'data: [DONE]') {
14
continue;
15
}
16
17
if (line.startsWith('data: ')) {
18
const message: Completion & { error?: { message: string } } = JSON.parse(line.substring('data: '.length));
19
20
if (message.error) {
21
throw new Error(message.error.message);
22
}
23
24
yield message;
25
}
26
}
27
}
28
29
// function replaceBytes(s: string): string {
30
// if (!s.startsWith('bytes:')) {
31
// return s;
32
// }
33
// const bytes: number[] = [];
34
// let i = 'bytes:'.length;
35
// const textEncoder = new TextEncoder();
36
// while (i < s.length) {
37
// if (s.slice(i, i + 3) === '\\\\x') {
38
// bytes.push(parseInt(s.slice(i + 3, i + 5), 16));
39
// i += 5;
40
// } else if (s.slice(i, i + 2) === '\\x') {
41
// bytes.push(parseInt(s.slice(i + 2, i + 4), 16));
42
// i += 4;
43
// } else {
44
// const encoded = textEncoder.encode(s.slice(i, i + 1));
45
// for (const b of encoded) {
46
// bytes.push(b);
47
// }
48
// i += 1;
49
// }
50
// }
51
// return new TextDecoder('utf8', { fatal: false }).decode(
52
// new Uint8Array(bytes)
53
// );
54
// }
55
56