Skip to content

Commit d52d954

Browse files
committed
fix: JSON parsing error of streaming "[DONE]" message
1 parent a9493fa commit d52d954

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

app/client/mlcllm.ts

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import log from "loglevel";
22
import { ChatOptions, LLMApi } from "./api";
3-
import { ChatCompletionFinishReason, CompletionUsage } from "@mlc-ai/web-llm";
3+
import {
4+
ChatCompletionFinishReason,
5+
CompletionUsage,
6+
ChatCompletion,
7+
} from "@mlc-ai/web-llm";
48

59
export class MlcLLMApi implements LLMApi {
610
private endpoint: string;
@@ -45,22 +49,29 @@ export class MlcLLMApi implements LLMApi {
4549
const chunk = new TextDecoder("utf-8").decode(value);
4650
const result = chunk.match(/data: (.+)/);
4751
if (result) {
48-
const data = JSON.parse(result[1]);
49-
if (data.choices && data.choices.length > 0) {
50-
reply += data.choices[0].delta.content; // Append the content
51-
options.onUpdate?.(reply, chunk); // Handle the chunk update
52+
try {
53+
const data = JSON.parse(result[1]);
54+
if (data.choices && data.choices.length > 0) {
55+
reply += data.choices[0].delta.content; // Append the content
56+
options.onUpdate?.(reply, chunk); // Handle the chunk update
5257

53-
if (data.choices[0].finish_reason) {
54-
stopReason = data.choices[0].finish_reason;
55-
}
58+
if (data.choices[0].finish_reason) {
59+
stopReason = data.choices[0].finish_reason;
60+
}
5661

57-
if (data.usage) {
58-
usage = data.usage;
62+
if (data.usage) {
63+
usage = data.usage;
64+
}
5965
}
66+
} catch (e) {
67+
log.error(
68+
"Error parsing streaming response from MLC-LLM server",
69+
e,
70+
);
6071
}
6172
}
6273

63-
if (chunk === "[DONE]") {
74+
if (chunk.includes("[DONE]")) {
6475
// Ending the stream when "[DONE]" is found
6576
break;
6677
}

0 commit comments

Comments
 (0)